我正在尝试在 SwiftUI 中播放背景声音。
我可以这样播放声音:
var aplayer = AVPlayer()
和
onAppear {
let aplayerItem = AVPlayerItem(url: URL(string: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")!)
aplayer = AVPlayer(playerItem: aplayerItem)
aplayer.play()
}
但是上面的代码有问题。
1- 它只循环一小段时间。
2- 如果我在视图之间导航,声音将停止。我知道这是因为我的代码在 .onAppear {...}
中。但是,即使视图发生变化,我如何使其可访问并继续播放?