AVAudioPlayer不能播放音乐与背景的NSTimer [英] AVAudioPlayer cannot play music with a NSTimer in background

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

问题描述

我想播放音乐使用的NSTimer的AVAudioPlayer,但 [播放器prepareToPlay] 返回NO&安培;在后台不玩了。

有人可以给我一些想法?

下面是我的code:

   - (BOOL)应用:(*的UIApplication)的应用didFinishLaunchingWithOptions:(NSDictionary的*)launchOptions
{
    [的NSTimer scheduledTimerWithTimeInterval:10目标:自我选择:@选择(playMusic :)用户信息:无重复:NO];
    [self.window makeKeyAndVisible]
    返回YES;
} - (无效)playMusic:(*的NSTimer)定时器{
    [AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback错误:无];
    的NSString *文件名= [[[一个NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@Apologize.mp3];
    NSURL * fileUrl = [NSURL fileURLWithPath:文件名]。
    NSError *错误;
    AVAudioPlayer *玩家= [[AVAudioPlayer页头] initWithContentsOfURL:fileUrl错误:&放大器;错误]
    如果([播放器prepareToPlay]){
        [播放器播放];
        的NSLog(@开始!);
    }其他{
        的NSLog(@错误信息:%@,错误);
    }
} - (无效)applicationDidEnterBackground:(UIApplication的*){应用    如果([[UIApplication的sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
        [UIApplication的sharedApplication] beginReceivingRemoteControlEvents]
    }    UIBackgroundTaskIdentifier backgroundTask = [[UIApplication的sharedApplication] beginBackgroundTaskWithExpirationHandler:^ {
    // / *如果发生这种情况只是失败。 * /
        [UIApplication的sharedApplication] endBackgroundTask:backgroundTask];
    }];
}


解决方案

您需要这样做的init在 viewDidLoad中

 的NSString * soundFilePath = [[一个NSBundle mainBundle] pathForResource:@测试
                                                          ofType:@MP3];
NSURL * fileURL = [[NSURL页头] initFileURLWithPath:soundFilePath];
self.audioPlayer = [[AVAudioPlayer页头] initWithContentsOfURL:fileURL
                                                          错误:无];
[UIApplication的sharedApplication] beginReceivingRemoteControlEvents][AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback错误:无];
[AVAudioSession sharedInstance] SETACTIVE:YES错误:无];

这是用于音频的初始化。在这里,一个名为MP3的测试的进口项目。
请注意,在 beginReceivingRemoteControlEvents 部分是非常重要的。没有它,你不能启动从后台播放,只是继续听音乐已经从前台播放。

现在你要听事件的 didEnterInBackGround (你可以与你的应用程序代理的 applicationDidEnterBackground 去,但这样一来就可以把code在类属于):

  [NSNotificationCenter defaultCenter]的addObserver:自我
                                         选择:@选择(didEnterBG :)
                                             名称:使用UIApplicationDidEnterBackgroundNotification
                                           对象:无];

而现在在 didEnterBG 方式:

  self.backgroundTimer = [的NSTimer scheduledTimerWithTimeInterval:10.0目标:自我选择:@selector(backgroundWork)USERINFO:无重复:YES];
[self.backgroundTimer火]

在这里,我让这个声音重复每10秒因个人原因,但做任何你需要的。
最后,在 backgroundWork 方式:

   - (无效){ba​​ckgroundWork
    [self.audioPlayer prepareToPlay]。
    [self.audioPlayer播放];
}

现在你的音频文件正在播放的背景: - )

您还应该注意到,您的应用程序需要有特定的权限要继续做的工作背景。你需要检查下YourTarget'盒子 - >功能 - >后台模式:音频和AirPlay。否则,操作系统将终止您在现实条件下几分钟应用程式(没有调试器或乐器)。

I want to play music with an AVAudioPlayer using an NSTimer, but [player prepareToPlay] returns NO & doesn't play in the background.

Can somebody give me some idea?

Here's my code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(playMusic:) userInfo:nil repeats:NO];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)playMusic:(NSTimer *)timer{
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    NSString *fileName = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Apologize.mp3"];
    NSURL *fileUrl = [NSURL fileURLWithPath:fileName];
    NSError *error;
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    if ([player prepareToPlay]) {
        [player play];
        NSLog(@"start!");
    }else{
        NSLog(@"error msg :%@",error);
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application {

    if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    }

    UIBackgroundTaskIdentifier backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    //        /* just fail if this happens. */
        [[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
    }];
}

解决方案

You need to do this init in the viewDidLoad :

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test"
                                                          ofType:@"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
                                                          error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

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

This is for the audio initialization. Here, with a MP3 named test, imported in the project. Note that the beginReceivingRemoteControlEvents part is very important. Without it, you cannot start playing from background, just keep on listening to music already playing from foreground.

Now you need to listen to the event didEnterInBackGround (you could go with the applicationDidEnterBackground of your app delegate, but this way you can put the code in the class it belongs to):

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(didEnterBG:)
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];

And now in that didEnterBG method :

self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(backgroundWork) userInfo:nil repeats:YES];
[self.backgroundTimer fire];

Here i make this sound repeat every 10s for personal reasons, but do whatever you need. Finally, the backgroundWork method :

- (void)backgroundWork{
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
}

Now your audio file is playing in background :-)

You should also note that your app need to have specific rights to keep doing jobs in background. You need to check the box under 'YourTarget' -> Capabilities -> Background Modes : Audio and AirPlay. Otherwise, the OS will terminate you app in a few minutes in real conditions (with no debugger or instrument).

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

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