SwiftUI AVPlayer 在按下 15 秒前进按钮后有时会停止播放

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

我构建了一个带有 15 秒前进和后退按钮的小型媒体播放器。如果我按下按钮,播放器有时会停止播放。

代码尽可能简单。但是我找不到问题。

欢迎任何提示:-)

缓冲问题可能吗?如果向前跳得比缓冲流更远,则流停止播放?

这是按钮和 MediaPlayer 类的 SwiftUI 代码...

  Button(action: {
                                if isSongPlaying {
                                    let playerCurrentTime = CMTimeGetSeconds((mediaPlayer.player!.currentTime()))
                                    let newTime = playerCurrentTime + 15
                                    let time2: CMTime = CMTimeMake(value: Int64(newTime * 1000 as Float64), timescale: 1000)
                                    mediaPlayer.player!.seek(to: time2, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
                                } })
                            {
                                
                                Image(systemName: "goforward.15")
                                    .foregroundColor(.primary)
                                    .font(.system(size: 50))
                                    .accessibility(label: Text(LocalizedStringKey(stringLiteral: "forward")))
                            }
                        }
                        .padding(.vertical, 5)






class MediaPlayer : ObservableObject {
    
    var player: AVPlayer?
    @Published var duration = 0.000
    
    func playStream(stream: String) {
        if let url = URL(string: stream) {
            self.player = AVPlayer(url: url)
        }
        
        duration = CMTimeGetSeconds(player!.currentItem!.asset.duration)
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
            player = AVPlayer(url: URL.init(string: stream)!)
            
            
            player?.play()
        } catch {
            fatalError("playback failed")
        }
    }
    
    func playing() {
        player?.play()
    }
    
    func pausePlaying() {
        player?.pause()
    }
    func stopPlaying() {
        player?.rate = 0
    }
}
´´´
swift swiftui avplayer
© www.soinside.com 2019 - 2024. All rights reserved.