ios - 如何启用 MPMediaItemArtwork 下一个/上一个按钮?

标签 ios objective-c audio avaudioplayer

我在我的项目中使用 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 :

enter image description here

enter image description here

注意:当我终止应用程序并再次运行、播放歌曲和锁定设备时,下一首和上一首按钮启用并起作用,但第一次不起作用。

那么我的问题是为什么第一次不启用下一个/上一个按钮?

提前致谢。

最佳答案

你能像下面这样定位上一个和下一个轨道对象吗

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/

相关文章:

ios - 如何以编程方式使用原型(prototype)单元格删除 TableView 节标题

ios - 以编程方式更改 UINavigationbar 背景颜色和标题字体/颜色

ios - 我可以一次访问 .xcassets 中的所有图像吗?

iphone - 如何在UILocalNotification中播放录制的声音

audio - 如何在Cocos2d中使用NSArray播放随机声音

node.js - 如何在 Node 中接收SIP音频并将WAV流发送到Google语音识别API?

ios - Xamarin - 无法再在设备上调试 - 错误 MT5211

ios - 从 UITableViewCell 中的 UITextField 访问文本

objective-c - 上传文件使用uploadTaskWithRequest :fromFile: in background and use multipart/form-data

c# - 如何将波信号分成帧