关于Swift:使用AVPlayer播放音频:Swift:使用AVPlayer播放音频-音频未播放,听不到音频

Swift: Playing audio using AVPlayer - Audio is not playing, cannot hear audio

我正在使用AVPlayer播放mp3音频文件。我正在使用经过测试且可以正常运行的网址。我需要使用AVPlayer,因为我需要以编程方式设置UISlider,并且AVPlayer很方便。 UISlider在音频播放时工作并更新。音频可能正在播放,但我听不到声音。我之所以这样说是因为UISlider正在工作。

更新:在模拟器上构建应用程序时,您可以听到音频。在设备上进行构建时发生问题-我的设备是XS MAX。

链接到屏幕记录ong->
访问:https://streamable.com/nkbn8

我尝试将相同的URL用于AVAudioPlayer和音频播放,并且您可以听到。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
        })
    }
}

预期结果:听到音频播放

实际结果:听不到音频播放。好像音频正在播放而没有声音。


使用AVPlayer时,应确保设备未处于静音模式,因为即使您的音量最大,也不会导致输出音频。

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

1
2
3
4
5
6
7
do {
            try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
        }
        catch {
            // report for an error
            print(error)
        }


我尝试使用最简单的版本,它可以在模拟器和设备(XS)上运行。

如@ N.Der所述,请检查类别模式。在这种情况下,在静音模式下,听不到声音。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import AVFoundation
import UIKit

final class ViewController: UIViewController {
    private var audioPlayer: AVPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupAudioContent()
    }

    private func setupAudioContent() {
        guard let url = URL(string:"https://s3.amazonaws.com/kargopolov/kukushka.mp3")
            else { return }

        audioPlayer = AVPlayer(url: url as URL)
        audioPlayer?.play()
    }
}

要轻松管理avplayer配置和所有中断,请尝试以下库:MordernAVPlayer