我正在使用AVPlayer仅播放一个mp3音频文件。我使用了一个已经测试过并且正常工作的url。我需要使用AVPlayer因为我需要编程设置一个UISlider并且AVPlayer很方便。UISlider可以工作并且在音频播放时更新。音频可能正在播放,但我听不到声音。我这么说是因为UISlider正在工作。
更新:在模拟器上构建应用程序时可以听到音频。问题出现在构建它的设备上——我的是XS MAX。
屏幕录制链接->访问:https://streamable.com/nkbn8 我尝试使用AVAudioPlayer和相同的URL播放音频,你可以听到它。
更新:在模拟器上构建应用程序时可以听到音频。问题出现在构建它的设备上——我的是XS MAX。
屏幕录制链接->访问:https://streamable.com/nkbn8 我尝试使用AVAudioPlayer和相同的URL播放音频,你可以听到它。
private func setupAudioContent() {
let urlString = "https://s3.amazonaws.com/kargopolov/kukushka.mp3"
if let url = NSURL(string: urlString) {
audioPlayer = AVPlayer(url: url as URL)
let playerLayer = AVPlayerLayer(player: audioPlayer)
self.layer.addSublayer(playerLayer)
playerLayer.frame = self.frame
audioPlayer?.play()
audioPlayer?.volume = 1.0
audioPlayer?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
let interval = CMTime(value: 1, timescale: 2)
audioPlayer?.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { (progressTime) in
let currentTime = CMTimeGetSeconds(progressTime)
let currentTimeSecondsString = String(format: "%02d", Int(currentTime.truncatingRemainder(dividingBy: 60)))
let currentTimeMinutesString = String(format: "%02d", Int(currentTime / 60))
self.currentTimeLabel.text = "\(currentTimeMinutesString):\(currentTimeSecondsString)"
if let duration = self.audioPlayer?.currentItem?.duration {
let durationsSeconds = CMTimeGetSeconds(duration)
self.audioSlider.value = Float(currentTime / durationsSeconds)
}
})
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "currentItem.loadedTimeRanges" {
isAudioPlaying = true
if let duration = audioPlayer?.currentItem?.duration {
let seconds = CMTimeGetSeconds(duration)
let secondsText = Int(seconds) % 60
let minutesText = String(format: "%02d", Int(seconds) / 60)
audioLengthLabel.text = "\(minutesText):\(secondsText)"
}
}
}
@objc func handleSliderChange() {
if let duration = audioPlayer?.currentItem?.duration {
let totalSeconds = CMTimeGetSeconds(duration)
let value = Float64(audioSlider.value) * totalSeconds
let seekTime = CMTime(value: Int64(value), timescale: 1)
audioPlayer?.seek(to: seekTime, completionHandler: { (completedSeek) in
})
}
}
期望结果:听到音频播放
实际结果:无法听到音频播放。似乎音频正在播放,但没有声音。