如何在 iOS 13 中流式传输远程音频?(SwiftUI)

Sea*_*rse 2 avplayer swift swift5 ios13 swiftui

此代码AVPlayer仅适用于Playground

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()

Run Code Online (Sandbox Code Playgroud)

当我尝试在物理设备上的 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")
          })
Run Code Online (Sandbox Code Playgroud)

它将Works打印到控制台。但是,它不会在设备上播放任何声音。

希望得到任何帮助,在这里找不到任何东西。

非常感谢!

Rob*_*ier 7

在 SwiftUI 中,视图是值类型。它们只是描述屏幕上事物的数据。它们可以随时创建、销毁或复制。AVPlayer 是对特定播放器对象的引用。您在这里假设它将继续存在,并且只会存在其中之一。这不是 SwiftUI 视图提供的东西。

您需要将您的 AVPlayer 移动到视图之外(进入模型对象),并将 UI 操作绑定到它。