iphone:在后台播放音频播放列表? [英] iphone: playing audio playlist in the background?

查看:27
本文介绍了iphone:在后台播放音频播放列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 AVAudioPlayer 在后台播放音频文件序列.当应用程序不在后台时它播放得很好,但是当应用程序进入后台时它不会播放第二首歌曲.

I'm trying to play sequence of audio files in the background using AVAudioPlayer. When the app is not in the background it plays well, but when the app goes to the background it won't play the second song.

这是我的代码:

-(void)playAudio:(NSString *)path{
    NSURL *url = [NSURL fileURLWithPath:path];

    NSError *error;
    AVAudioPlayer *ap = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    ap.delegate = self;

    mainController.audioPlayer = ap;
    [ap release];


    if (mainController.audioPlayer == nil)
        NSLog([error description]);
    else{


        UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;

        [mainController.audioPlayer prepareToPlay];

        if([mainController.audioPlayer play]){

            newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

        }

        if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid)
            [[UIApplication sharedApplication] endBackgroundTask: bgTaskId];

        bgTaskId = newTaskId;
    }

}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"finished now next...");
    [self playAudio:[self getNextAudio]];

}

我调试了应用程序,似乎在要播放第二首歌曲时[mainController.audioPlayer play] 返回NO,这意味着它无法播放.那你怎么看?

I debugged the app and it seems that when it's about to play the second song [mainController.audioPlayer play] returns NO, which means it can't play. So what do you think?

更新

经过一些测试,似乎只有在设备锁定时它才能继续正常播放,但是如果用户按下主页按钮并且应用程序进入后台,问题仍然存在

After some testing it seems that it does continue to play properly only if the device locks, but if the user presses the home button and the app goes to the background the problem still remains

推荐答案

THE SOLUTION

THE SOLUTION

只需添加 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 和其他一些调整.都在这里

Just add [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; and some other tweaks. It's all here

https://devforums.apple.com/message/264397

这篇关于iphone:在后台播放音频播放列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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