如何设置 AVPlayer 的音量

How to set volume for AVPlayer

我正在尝试为 AVPlayer 设置音量,但它似乎不起作用。它占用系统音量并忽略代码中设置的值。以下是我的代码。我们如何设置音量级别?

let player = AVPlayer(url: URL(string:recordingFileURL)!)
let playerController = AVPlayerViewController()
playerController.player = player
playerController.videoGravity = AVLayerVideoGravity(rawValue: AVLayerVideoGravity.resizeAspectFill.rawValue)

self.present(playerController, animated: true) {
    player.play()
    player.volume = 0.8 // Doesn't have any affect
}

Apple Docs 说这是不可能的。

This property is used to control the player audio volume relative to the system volume. There is no programmatic way to control the system volume in iOS, but you can use the MediaPlayer framework’s MPVolumeView class to present a standard user interface for controlling system volume.

由于AVPlayer的音量是相对于系统音量的,所以你永远不能强制AVPlayer的播放音量大于系统音量。

您在评论中说:

My assumption was that the value set in above code should overwrite the system volume's value

这个假设是错误的。如果系统音量为 0.2 而您将播放器的音量设置为 0.8,那么您所做的只是让播放器更柔和 (0.16)。正如 the documentation 告诉你的:

This property is used to control the player audio volume relative to the system volume. There is no programmatic way to control the system volume in iOS.

player.volume = 0.8

此 属性 在 iOS 上最有用,可用于控制 AVSampleBufferAudioRenderer 相对于其他音频输出的音量,而不是用于设置绝对音量。