为什么我暂停AVAudioPlayer时锁屏audio控制消失?

我正在使用AVAudioPlayer的实例来播放audio文件。 该应用程序被configuration为在后台播放audio,并设置适当的audio会话。 我也成功接收远程控制事件。

代码如下:

#import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface ViewController () @property (nonatomic) AVAudioPlayer *player; @end @implementation ViewController @synthesize player; - (BOOL)canBecomeFirstResponder { return YES; } - (void)viewDidLoad { [super viewDidLoad]; // Turn on remote control event delivery [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; // Set ourselves as the first responder [self becomeFirstResponder]; // Set the audio session AVAudioSession *audioSession = [AVAudioSession sharedInstance]; NSError *setCategoryError = nil; BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError]; NSError *activationError = nil; success = [audioSession setActive:YES error:&activationError]; // Play an mp3 with AVAudioPlayer NSString *audioFileName = @"%@/Via_Aurora.mp3"; NSURL *audioURL = [NSURL fileURLWithPath:[NSString stringWithFormat:audioFileName, [[NSBundle mainBundle] resourcePath]]]; player = [[AVPlayer alloc] initWithURL:audioURL]; [player play]; } - (void)viewWillDisappear:(BOOL)animated { // Turn off remote control event delivery & Resign as first responder [[UIApplication sharedApplication] endReceivingRemoteControlEvents]; [self resignFirstResponder]; // Don't forget to call super [super viewWillDisappear:animated]; } - (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent { if (receivedEvent.type == UIEventTypeRemoteControl) { switch (receivedEvent.subtype) { case UIEventSubtypeRemoteControlPreviousTrack: NSLog(@"prev"); break; case UIEventSubtypeRemoteControlNextTrack: NSLog(@"next"); break; case UIEventSubtypeRemoteControlPlay: [player play]; break; case UIEventSubtypeRemoteControlPause: [player pause]; break; default: break; } } } @end 

当我运行应用程序时,audio播放视图加载时。 应用程序在进入后台模式时继续播放audio。 我能够成功暂停和/或播放控制中心的audio(可以从应用程序或locking屏幕访问),但是,如果访问locking屏幕audio控件并暂停播放器,则音乐暂停并locking屏幕控件消失。 我期望音乐暂停,但不是控制消失。

在我使用的其他audio应用程序中,您可以暂停,然后播放来自locking屏幕的audio。 我忽略了什么? 这是做这种事情的正确方法吗?

你在正确的轨道上

你似乎缺less设置;

  MPNowPlayingInfoCenter nowPlayingInfo 

没有它,你会得到所述的结果,IE暂停后,locking屏幕不再显示暂停,或确实是它正在播放一首歌曲。 这里有一个关于如何设置它的指南(我已经从一段时间的工作代码中获取了这个信息,但是我相信你能弄清楚是什么)。

  MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc]initWithImage:albumImage]; [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = [NSDictionary dictionaryWithObjectsAndKeys:aSong.songTitle, MPMediaItemPropertyTitle, aSong.artistName, MPMediaItemPropertyArtist, artwork, MPMediaItemPropertyArtwork, 1.0f, MPNowPlayingInfoPropertyPlaybackRate, nil]; 

在ViewDidLoad()中添加此代码用于后台播放。 它为我工作。 你应该试试

  UIApplication.sharedApplication().beginReceivingRemoteControlEvents() let session:AVAudioSession = AVAudioSession.sharedInstance() do { try session.setCategory(AVAudioSessionCategoryPlayback) } catch { print("Background Play Error") }