AVAudioEngine 和 AVAudioPlayerNode:播放/暂停未在 iOS 命令中心正确更新

问题描述

我已阅读Play/Pause and Elapsed Time not updating in iOS command center properly

我尝试过 MPNowPlayingInfoPropertyElapsedplaybackTimeMPNowPlayingInfoPropertyDefaultPlaybackRateMPNowPlayingInfoPropertyPlaybackRate

我已经更新了 apple demo

苹果演示可以在iOS命令中心显示播放/暂停更新,AVPlayer

这里使用 AVAudioEngineAVAudioPlayerNodeAVAudioPlayerNode 通过 scheduleBuffer 播放音频

这里是相关的iOS命令中心代码

func show(mediaInfo time: TimeInterval){
        let artistName = "test"
        
        guard let duration = length else {
            return
        }
        var isPlaying: Double = 0
        
        var pInfo: [String: Any] = [MPMediaItemPropertyArtist : artistName,MPMediaItemPropertyTitle : artistName ]
        if let img = UIImage(systemName: "music.note.list"){
            let artwork = MPMediaItemArtwork(boundsSize: img.size,requestHandler: {  (_) -> UIImage in
                return img
            })
            pInfo[MPMediaItemPropertyArtwork] = artwork
            
        }
        
        if streamer.state == .playing{
            isPlaying = 1
            pInfo[MPNowPlayingInfoPropertyElapsedplaybackTime] = time
            pInfo[MPMediaItemPropertyPlaybackDuration] = duration
        }
        pInfo[MPMediaItemPropertyPersistentID] = artistName
        pInfo[MPNowPlayingInfoPropertyPlaybackRate] = NSNumber(floatLiteral: isPlaying)
        pInfo[MPNowPlayingInfoPropertyDefaultPlaybackRate] = NSNumber(floatLiteral: isPlaying)
        pInfo[MPNowPlayingInfoPropertyMediaType] = NSNumber(value: MPNowPlayingInfoMediaType.audio.rawValue)
        MPNowPlayingInfoCenter.default().NowPlayingInfo = pInfo
    }

这里是the example code


对应的音频会话:

func setupAudioSession() {
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setCategory(.playback,mode: .default,policy: .default,options: [.allowBluetoothA2DP,.defaultToSpeaker])
            try session.setActive(true)
        } catch {
            os_log("Failed to activate audio session: %@",log: ViewController.logger,type: .default,#function,#line,error.localizedDescription)
        }
    }

也试过了

let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setCategory(AVAudioSession.Category.playAndRecord,options: AVAudioSession.CategoryOptions.defaultToSpeaker)
            audioSession.requestRecordPermission({ (isGranted: Bool) in
                
            })
        } catch  {}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)