ios - App 在后台时不播放声音(prepareToPlay 返回 NO)

标签 ios objective-c avaudioplayer

我在后台使用 AVAudioPlayer 在 iPhone 上播放声音文件(wav 文件)时遇到了一个奇怪的问题。我正在使用以下代码:

        AVAudioPlayer* audioplayer;
        NSError* error;

        audioplayer = [[AVAudioPlayer alloc] initWithData:soundfile error:&error];
        if (error) {
            NSLog(@"an error occured while init audioplayer...");
            NSLog(@"%@", [error localizedDescription]);
        }
        audioplayer.currentTime = 0;
        if (![audioplayer prepareToPlay])
            NSLog(@"could not preparetoPlay");

        audioplayer.volume = 1.0;

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

        if (![audioplayer play])
            NSLog(@"could not play sound");

        audioplayer.delegate = [myApp sharedInstance];

当应用程序处于前台时,这可以正常工作。但是,当将应用程序移动到后台时 [audioplayer prepareToPlay] 返回 NO。

这种情况发生在 AND 没有将“应用播放音频”添加到“必需的背景模式”的情况下。有没有办法从 [audioplayer prepareToPlay] 获得更精确的错误报告?或者您是否有任何提示我做错了什么或忘记了什么?

最佳答案

您需要在准备 AVAudioPlayer 实例之前初始化您的 Audio Session 。理想情况下,将 Audio Session 调用移至应用程序委托(delegate)的 didFinishLaunchingWithOptions 方法。

关于ios - App 在后台时不播放声音(prepareToPlay 返回 NO),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16266112/

相关文章:

ios - 箭头 anchor 无法在 swift 中正确显示

ios - 自动调整 UITableView 高度以仅显示存在的 UITableViewCell

objective-c - RestKit - POST 响应对象映射

ios - 使用 URL Scheme 打开 IOS 应用程序并传递注册数据

ios - 无法获取 navigationItem.rightBarButtonItem 的 UIView/Frame - iOS

iphone - 带有目标的标签到另一个 View

iphone - NS_BLOCK_ASSERTIONS 是否同时禁用 NSAssert 和 assert() 调用?

ios - 如何从文档目录访问音频文件?

ios - 是否可以在后台模式下播放avaudioplayer?

ios - 如何在特定时间播放音频时调用 Action ?