美文网首页
Swift 锁屏界面操控播放的音乐

Swift 锁屏界面操控播放的音乐

作者: CYC666 | 来源:发表于2023-04-03 18:04 被阅读0次
    
            // 锁屏进度控制
            let center = MPRemoteCommandCenter.shared()
            
            // 修改进度
            center.changePlaybackPositionCommand.addTarget { event in
                
                guard let event = event as? MPChangePlaybackPositionCommandEvent else {
                    return .commandFailed
                }
                
                aVplayer.seek(to: CMTime(seconds: event.positionTime, preferredTimescale: 1),
                                   toleranceBefore: CMTime(seconds: 0, preferredTimescale: 1),
                             toleranceAfter: CMTime(seconds: 0, preferredTimescale: 1))
                
                // 更新锁屏信息
                return .success
            }
            
            // 播放
            center.playCommand.addTarget { event in
                
                self.continuePlayMusicAction()    
                return .success
            }
            
            // 暂停
            center.pauseCommand.addTarget { event in
                
                self.pauseMusicAction()
                return .success
            }
            
            // 下一首
            center.nextTrackCommand.addTarget { event in
                
                self.playerEndAction()
                return .success
            }
            
            // 上一首
            center.previousTrackCommand.addTarget { event in
                
                self.playerPreviousAction()
                return .success
            }
    
    
    
        // MARK: 更新锁屏界面的播放信息
        @objc private func updateScreenInfoAction(model: MusicProjectPlayInfoModel, to: Double = 0.0) {
            
            
            var dic = [String:Any]()
            dic[MPMediaItemPropertyTitle] = model.name
            dic[MPNowPlayingInfoPropertyElapsedPlaybackTime] = to
            dic[MPNowPlayingInfoPropertyPlaybackRate] = model.player.rate
            
            // 获取时长。item.duration.seconds 不凑效
            if model.url != nil {
                let asset = AVURLAsset.init(url: model.url!)
                dic[MPMediaItemPropertyPlaybackDuration] = CMTimeGetSeconds(asset.duration)
            }
            
            MPNowPlayingInfoCenter.default().nowPlayingInfo = dic
    
        }
    
    

    相关文章

      网友评论

          本文标题:Swift 锁屏界面操控播放的音乐

          本文链接:https://www.haomeiwen.com/subject/qocjddtx.html