I have read Play/Pause and Elapsed Time not updating in iOS command center properly
I have tried MPNowPlayingInfoPropertyElapsedPlaybackTime
, MPNowPlayingInfoPropertyDefaultPlaybackRate
and MPNowPlayingInfoPropertyPlaybackRate
.
I have updated the apple demo
The apple demo is OK to show Play/Pause updating in iOS command center, with AVPlayer
Here is using AVAudioEngine
and AVAudioPlayerNode
, AVAudioPlayerNode
plays audio by scheduleBuffer
.
Here is the relevant iOS command center code:
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
}
here is the example code
The corresponding audio session:
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)
}
}
also tried
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSession.Category.playAndRecord, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
audioSession.requestRecordPermission({ (isGranted: Bool) in
})
} catch {}
You can try stop AVAudioEngine. like this:
engine.stop()