AVAudioEngine 和 AVAudioPlayerNode:Play/Pause 未在 iOS 命令中心正确更新

AVAudioEngine and AVAudioPlayerNode: Play/Pause not updating in iOS command center properly

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

我试过MPNowPlayingInfoPropertyElapsedPlaybackTimeMPNowPlayingInfoPropertyDefaultPlaybackRateMPNowPlayingInfoPropertyPlaybackRate

我更新了apple demo

Apple 演示可以在 iOS 命令中心显示 Play/Pause 更新,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  {}

您可以试试停止AVAudioEngine。 像这样:

engine.stop()

更好用engine.pause()

   public func pause(){

        // Check if the player node is playing
        guard playerNode.isPlaying else {
            return
        }
        
        // Pause the player node and the engine
        playerNode.pause()
        
        // Update the state
        state = .paused
        engine.pause()
    }