使用 SwiftUI,我有一个自定义的 avplayer,可以自动播放和循环视频。问题是无论我是否特意告诉avplayer取消静音,它仍然是静音的。物理音量按钮没有任何作用。打开/关闭静音的唯一方法是将铃声物理切换为静音(静音)或非静音(取消静音)。
这是父视图:
struct VideoCacheView: View {
@State private var avPlayer: AVPlayer? = nil
public let url: String
public let thumbnailURL: String
var body: some View {
if self.avPlayer != nil {
CustomVideoPlayer(player: Binding(self.$avPlayer)!)
.onAppear {
self.avPlayer?.isMuted = false
self.avPlayer?.play()
}
}
}
}
和孩子:
struct CustomVideoPlayer: UIViewControllerRepresentable {
@EnvironmentObject var cvm: CameraViewModel
@Binding var player: AVPlayer
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeUIViewController(context: Context) -> AVPlayerViewController {
let controller = AVPlayerViewController()
controller.player = self.player
controller.showsPlaybackControls = false
controller.videoGravity = self.cvm.videoGravity
player.actionAtItemEnd = .none
NotificationCenter.default.addObserver(context.coordinator, selector: #selector(context.coordinator.restartPlayback), name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
return controller
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) { }
class Coordinator: NSObject {
public var parent: CustomVideoPlayer
init(_ parent: CustomVideoPlayer) {
self.parent = parent
}
@objc func restartPlayback () {
self.parent.player.seek(to: .zero)
}
}
}
为什么我的AV播放器唯一的音量控制是物理静音开关?
https://developer.apple.com/documentation/avfoundation/avplayer/1390127-volume
原来铃声处于静音模式时音量设置为0.0。默认将音量设置为1.0,则始终有音量。
添加了这个:
self.player?.volume = 1.0
视频重力线下方的子视图内部
这可以通过将
AVAudioSession
类别设置为 .playback
来完成:
try? AVAudioSession.sharedInstance().setCategory(.playback)
player.play()