iphone - AVAudioPlayer在后台播放

标签 iphone ios avaudioplayer background-process

根据我们的要求,即使应用程序处于后台,我们也需要播放声音。我们正在使用[AVAudioPlayer Play]来播放声音。

如果应用程序在前台,它将起作用。但是,如果应用程序在后台运行,并且我们也在音乐播放器中播放歌曲,然后控制权转到[AVAudioPlayer Play]语句,则什么也不会发生。

我们已经遍历了许多链接,在plist中添加了背景模式,还添加了[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];,但是事情没有解决。

请提出是否还有其他选择。

最佳答案

只需在初始化AVAudioPlayer实例的位置添加以下三行:

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

AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

// These lines need to be added:

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

[audioPlayer play];

关于iphone - AVAudioPlayer在后台播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14874594/

相关文章:

iphone - 在为 iOS 设备(iPhone、iPad)上的 Epson POS TM-T88 编写收据打印机驱动程序时需要帮助吗?

iphone - 为 iPhone 应用程序生成类图

ios - 访问 iPod 库以与 AVAudioPlayer 一起使用或使用 AVPlayer 远程控制事件

iphone - 如何在 AVAudioPlayer 中静音?

objective-c - 未安装 Sim 卡弹出在调用功能中显示两次

iphone - 在开发者设备上安装以前版本的 iOS(目前是 5.0 -> 需要 4.3.5)

ios - 如何将 subview 添加到 TableViewCell?

ios - 将从图库中选择的照片显示到表格 View 中

iphone - 发布包含 UIImage 的 Facebook 链接

ios - 嗨,有没有办法让 AVSpeech 合成器在使用耳机播放音频的同时使用任一 channel 播放音频?