指挥中心/动态岛缺少图标和动画

问题描述 投票:0回答:1

我正在我的 swiftui 应用程序中设置一个非常简单的媒体播放器。

代码如下:

import AVFoundation
import MediaPlayer

class AudioPlayerProvider {
    private var player: AVPlayer
    
    init() {
        self.player = AVPlayer()
        self.player.automaticallyWaitsToMinimizeStalling = false
        
        self.setupAudioSession()
        self.setupRemoteCommandCenter()
    }
    
    private func setupAudioSession() {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print("Failed to set up audio session: \(error.localizedDescription)")
        }
    }
    
    private func setupRemoteCommandCenter() {
        let commandCenter = MPRemoteCommandCenter.shared()
        
        commandCenter.playCommand.addTarget { [weak self] _ in
            guard let self = self else { return .commandFailed }
            self.play()
            return .success
        }
        
        commandCenter.pauseCommand.addTarget { [weak self] _ in
            guard let self = self else { return .commandFailed }
            self.pause()
            return .success
        }
    }
    
    func loadAudio(from urlString: String) {
        guard let url = URL(string: urlString) else { return }
        
        let asset = AVAsset(url: url)
        
        let playerItem = AVPlayerItem(asset: asset)
        
        self.player.pause()
        self.player.replaceCurrentItem(with: playerItem)
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.streamFinished), name: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem)
    }
    
    func setMetadata(title: String, artist: String, duration: Double) {
        var nowPlayingInfo = [
            MPMediaItemPropertyTitle: title,
            MPMediaItemPropertyArtist: artist,
            MPMediaItemPropertyPlaybackDuration: duration,
            MPNowPlayingInfoPropertyPlaybackRate: 1.0,
           
        ] as [String: Any]
        
        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
    }
    
    @objc
    private func streamFinished() {
        self.player.seek(to: .zero)
        
        try? AVAudioSession.sharedInstance().setActive(false)
        
        MPNowPlayingInfoCenter.default().playbackState = .stopped
    }
    
    func play() {
        MPNowPlayingInfoCenter.default().playbackState = .playing
            
        self.player.play()
    }
    
    func pause() {
        MPNowPlayingInfoCenter.default().playbackState = .paused
            
        self.player.pause()
    }
}

很有学术性。

该代码在视图上调用时有效。它也会显示在锁屏/动态岛中(在后台时),但问题在于:

  • 播放/暂停按钮既不会出现在命令中心,也不会出现在动态岛上。如果我点击这些按钮应该显示的位置,该命令就会起作用。只是图标没有出现。
  • 播放时波形动画没有动画。

许多音频应用程序运行良好,所以我的代码是否缺少一些东西。但我不知道为什么。 缺少什么?

swift swiftui avplayer
1个回答
0
投票

好吧,最终问题仅限于模拟器上。在真实设备上工作没有任何问题

© www.soinside.com 2019 - 2024. All rights reserved.