ios - 通知控制中心同时播放多个音频

标签 ios swift avplayer avaudiosession mpremotecommandcenter

我有一个场景,当我播放单个音频文件并移动到控制中心时,它工作正常,但如果返回 View Controller (在那里调用player.pause())并返回并尝试其他文件,它可以工作在同一 Controller 上,但在控制中心,上一个文件也同时播放。

可能是因为 AVPlayer 对象,我的处理程序调用了多次。

MPRemoteCommandCenter.shared().playCommand.addTarget { (playEvent) -> MPRemoteCommandHandlerStatus in
        let currentItem = self.player.currentItem
        self.player.replaceCurrentItem(with: currentItem)
        if self.player.isPlaying {
            self.player.pause()
        }else{
            self.player.play()
        }
        self.updateInfo()
        self.btnAudioPlay.setImage(#imageLiteral(resourceName: "pause"), for: .normal)
        return .success
    }

MPRemoteCommandCenter.shared().pauseCommand.addTarget { (pauseEvent) -> MPRemoteCommandHandlerStatus in
        if self.player.isPlaying {
            self.player.pause()
        }else{
            self.player.play()
        }
        self.updateInfo()
        self.btnAudioPlay.setImage(#imageLiteral(resourceName: "play"), for: .normal)
        return .success
    }

func updateInfo() {
    let image = UIApplication.shared.icon!
    let mediaArtwork = MPMediaItemArtwork(boundsSize: image.size) { (size: CGSize) -> UIImage in
        return image
    }

    let nowPlayingInfo: [String: Any] = [
        MPMediaItemPropertyAlbumTitle: self.subTilteForAudioPlayer,
        MPMediaItemPropertyTitle: self.titleForAudioPlayer,
        MPMediaItemPropertyArtwork: mediaArtwork,
        MPMediaItemPropertyPlaybackDuration:  Float(CMTimeGetSeconds((player.currentItem?.asset.duration)!)) ,
        MPNowPlayingInfoPropertyElapsedPlaybackTime: Float(CMTimeGetSeconds(player.currentTime()))
    ]
    MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}

最佳答案

音频播放器每次都会初始化,它出现在同一屏幕上,因此通知中心会播放多个声音。

player = nil

上面的代码对我有用。

关于ios - 通知控制中心同时播放多个音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50637406/

相关文章:

ios - OpenCart客户密码加密

ios - 在 MVVM 中处理来自 UITableViewCell 的 Action

ios - 使用WKWebView获取嵌入网页的视频url

swift - 使用 Swifty 在 Swift 中将 JSON 作为字符串返回

ios - 响应没有 'Content-Lenght' header 时的 AVURLAsset

iTunes Match + AVplayer + MPMediaQuery 不工作

iOS:从浏览器后台播放?

objective-c - Swift 中正确的 block 语法是什么

swift - 使用 RKValueTransFormer 将 NSArray 转换为 RLMArray 无法将 outputValue 转换为 AutoreleasingUnsafeMutablePointer<AnyObject?>

AVPlayer seekToTime :toleranceBefore:toleranceAfter hangs Intermittently