我在后台模式下播放 AVPlayer 时遇到问题,就像网络上到处都有很多人一样。我已经完成了我认为应该工作的事情,但仍然没有......我认为我的问题可能出在我设置和使用我的 AudioSession 和 AVPlayer 的地方。
1)“音频”键在我的 Info.plist 的 UIBackgroundModes 中
2)在 AppDelegate 中这样设置的 AudioSession(在 didFinishLaunchingWithOptions 中初始化):
AVAudioSession *audio = [[AVAudioSession alloc]init];
[audio setCategory:AVAudioSessionCategoryPlayback error:nil];
[audio setActive:YES error:nil];
3)我使用在 AppDelegate 中也实现的 AVPlayer(不是 AVAudioPlayer)。(在 didFinishLaunchingWithOptions 中初始化,在 AudioSession 之后),就在 AudioSession 之后
// Load the array with the sample file
NSString *urlAddress = @"http://mystreamadress.mp3";
//Create a URL object.
self.urlStream = [NSURL URLWithString:urlAddress];
self.player = [AVPlayer playerWithURL:urlStream];
//Starts playback
[player play];
而且,每次应用程序进入后台时(当我按下“主页”按钮时),音频都会暂停。