如何在背景iphone sdk播放音乐 [英] How to play music in background iphone sdk

查看:135
本文介绍了如何在背景iphone sdk播放音乐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,我已经在应用程序中设置了计时器,之后我进入后台,当时间结束时我想在后台播放音乐。但是音乐不能播放?

I am working on an app,i have set timer in app, after that i went in background and when time is over i want to play music in background.but music is not play?

推荐答案

使用此定时器代码设置定时器

Use this Timer Code for set the Timer

UIBackgroundTaskIdentifier bgTask =0;
UIApplication  *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask]; 
}];

 self.secondsTimer = [NSTimer 
                         scheduledTimerWithTimeInterval:1 
                         target:self 
                         selector:@selector(timerFireMethod:) 
                         userInfo:nil 
                         repeats:NO];

fire方法 - - (void)timerFireMethod:(NSTimer *)theTimer
{}

fire Method-- (void) timerFireMethod:(NSTimer *) theTimer {}

在此火灾方法中使用以下代码播放媒体文件 -

In This fire Method use Below Code for Playing media file-

NSURL * url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@tujhbinjena
ofType:@mp3]];

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
               initWithContentsOfURL:url
               error:&error];
audioPlayer.delegate=self;
audioPlayer.volume=1.0;
if (error)
{
    NSLog(@"Error in audioPlayer: %@", 
          [error localizedDescription]);
} else {
    audioPlayer.delegate = self;
    [audioPlayer prepareToPlay];
    [audioPlayer play]
}`  




[self becomeFirstResponder];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];

[self becomeFirstResponder]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; [[AVAudioSession sharedInstance] setActive: YES error: nil];



- (BOOL)canBecomeFirstResponder {
    return YES;
}

以及 ViewDidUnload 您需要执行以下操作行

and in ViewDidUnload you need to do these following lines

[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];

你需要处理 AVAudioPlayerDelegate 委托方法和播放音频在后台,您需要在 Info.plist 中添加一个参数即所需的背景模式,此键的值为应用播放音频 。如有任何疑问,请告诉我。

you need to handle the AVAudioPlayerDelegate delegate methods as per and for playing audio in background you need to add one Parameter in Info.plist That is "Required background modes" and value for this key is "App plays audio". Please let me know if any doubt.

这篇关于如何在背景iphone sdk播放音乐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆