在iOS中控制应用程序外部的音频
我正在尝试从应用程序外部控制我的音频播放器, 我启动了一个av音频会话,但没有在后台播放(在swift 3上运行良好) 我的主要目标是像这样控制播放和暂停:在iOS中控制应用程序外部的音频,ios,swift,audio,avfoundation,Ios,Swift,Audio,Avfoundation,我正在尝试从应用程序外部控制我的音频播放器, 我启动了一个av音频会话,但没有在后台播放(在swift 3上运行良好) 我的主要目标是像这样控制播放和暂停: 因此,您正在构建一个应用程序,使用AVPlayer在后台播放音频。您应该使用mpnowplayingfocenter在锁定屏幕和控制中心上显示歌曲的元数据,并使用MPRemoteCommandCenter控制锁定屏幕和控制中心上的上一个/下一个/播放/暂停动作 启用音频、播放和图片的背景模式 在您的目标>功能中描绘 如果您正在从web流式
因此,您正在构建一个应用程序,使用
AVPlayer
在后台播放音频。您应该使用mpnowplayingfocenter
在锁定屏幕和控制中心上显示歌曲的元数据,并使用MPRemoteCommandCenter
控制锁定屏幕和控制中心上的上一个/下一个/播放/暂停动作
- 启用音频、播放和图片的背景模式 在您的目标>功能中描绘
- 如果您正在从web流式传输音频,请也为后台提取启用后台模式
- 导入
和AVKit
依赖项MediaPlayer
AVPlayerItem
设置您的AVPlayer
:
guard let url = URL(string: "http://your.website.com/playlist.m3u8") else {
return
}
player = AVPlayer(url: url)
设置您的音频会话
:
private func setupAVAudioSession() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
debugPrint("AVAudioSession is Active and Category Playback is set")
UIApplication.shared.beginReceivingRemoteControlEvents()
setupCommandCenter()
} catch {
debugPrint("Error: \(error)")
}
}
设置信息中心
和远程命令中心
:
private func setupCommandCenter() {
MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyTitle: "Your App Name"]
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.pauseCommand.isEnabled = true
commandCenter.playCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
self?.player.play()
return .success
}
commandCenter.pauseCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
self?.player.pause()
return .success
}
}
您可以将setupAVAudioSession()
方法放在viewDidLoad()
方法中,或者放在您需要的任何其他位置
如果需要在
mpnowplayingfocenter
中放置更多信息,以下是所有可用属性的列表:使用MPRemoteCommandCenter
。比较:我不知道为什么这个答案没有更多的投票。非常有用的信息。谢谢!
private func setupCommandCenter() {
MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyTitle: "Your App Name"]
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.pauseCommand.isEnabled = true
commandCenter.playCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
self?.player.play()
return .success
}
commandCenter.pauseCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
self?.player.pause()
return .success
}
}