使用AVPlayer
的此代码仅在游乐场
import AVFoundation
var player = AVPlayer()
let playerItem = AVPlayerItem(url: URL(string: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")!)
player = AVPlayer(playerItem: playerItem)
player.play()
当我尝试在物理设备上的SwiftUI应用上运行它时,使用以下代码:
Button(action:{
var player = AVPlayer()
let playerItem = AVPlayerItem(url: URL(string: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")!)
player = AVPlayer(playerItem: playerItem)
player.play()
print("Works")
},label:{
Image("play")
})
它将 Works 打印到控制台。但是,它不会在设备上播放任何声音。
不胜感激,在这里找不到任何东西。
非常感谢您!
答案 0 :(得分:3)
在SwiftUI中,视图是值类型。它们只是描述屏幕上事物的数据。它们可以随时创建,销毁或复制。 AVPlayer是对特定播放器对象的引用。您在这里假设它将继续存在,并且只有其中之一。那不是SwiftUI视图提供的。
您需要将AVPlayer移到View之外(移到Model对象中),然后将UI动作绑定到该视图。