我在我的项目中使用 AVAudioPlayer
。
当应用程序进入后台或锁定设备应用程序时,使用 AVAudioPlayer
播放歌曲。
我的问题是,当我下载 2 首歌曲并使用 AVAudioPlayer
播放歌曲并锁定设备时,歌曲将播放但下一首和上一首按钮被禁用。
我尝试使用波纹管代码启用按钮:
[MPRemoteCommandCenter sharedCommandCenter].previousTrackCommand.enabled = YES;
[MPRemoteCommandCenter sharedCommandCenter].nextTrackCommand.enabled = YES;
同时设置波纹管代码:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
然后像这样设置 MPMediaItemArtwork
细节:
MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"icon.png"]];
[songInfo setObject:@"song title" forKey:MPMediaItemPropertyTitle];
[songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
我还启用了 BackgroundMode
从 App Capability :
注意:当我终止应用程序并再次运行、播放歌曲和锁定设备时,下一首和上一首按钮启用并起作用,但第一次不起作用。
那么我的问题是为什么第一次不启用下一个/上一个按钮?
提前致谢。
最佳答案
你能像下面这样定位上一个和下一个轨道对象吗
MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
commandCenter.previousTrackCommand.enabled = YES;
commandCenter.nextTrackCommand.enabled = YES;
[commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
NSLog(@"Next Track");
return MPRemoteCommandHandlerStatusSuccess;
}];
[commandCenter.previousTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
NSLog(@"Previous Track");
return MPRemoteCommandHandlerStatusSuccess;
}];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//或
[commandCenter.nextTrackCommand addTarget:self action:@selector(play)];
[commandCenter.previousTrackCommand addTarget:self action:@selector(play)];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
您的代码看起来不错...!
关于ios - 如何启用 MPMediaItemArtwork 下一个/上一个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51925437/