Swift:使用AVPlayer播放音频 - 音频未播放,听不到声音。

4
我正在使用AVPlayer仅播放一个mp3音频文件。我使用了一个已经测试过并且正常工作的url。我需要使用AVPlayer因为我需要编程设置一个UISlider并且AVPlayer很方便。UISlider可以工作并且在音频播放时更新。音频可能正在播放,但我听不到声音。我这么说是因为UISlider正在工作。
更新:在模拟器上构建应用程序时可以听到音频。问题出现在构建它的设备上——我的是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
        })
    }
}

期望结果:听到音频播放

实际结果:无法听到音频播放。似乎音频正在播放,但没有声音。

1个回答

14

使用AVPlayer时,您应确保设备不处于静音模式,否则即使音量最大也会导致无法输出音频。

如果您希望将设备保持在静音模式下并仍然播放音频,则可以在 .play() 之前使用以下代码:

do {
            try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
        }
        catch {
            // report for an error
            print(error)
        }

1
谢谢,这对我很有效。当您使用try?时,您不需要用do catch包围调用 :) - sinalco12
我的设备没有静音,但仍然没有声音。还有其他建议吗?(顺便说一句:为什么要覆盖用户选择将设备设置为静音模式的选项呢?) - MultiGuy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接