【问题标题】:Multiple audios are playing simultaneously from notification control center从通知控制中心同时播放多个音频
【发布时间】:2018-06-01 06:35:06
【问题描述】:

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

可能是因为 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
}

【问题讨论】:

    标签: ios swift avplayer avaudiosession mpremotecommandcenter


    【解决方案1】:

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

    player = nil
    

    上面的代码对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多