How to stream remote audio in iOS 13? (SwiftUI)

岁酱吖の 提交于 2019-12-20 05:26:16

问题


This code using AVPlayer works only on 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()

When I tried to run it on my SwiftUI App on my physical device, using this code:

 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")
          })

It prints Works to the console. However, it does not play any sound on the device.

Would appreciate any help, can't find anything yet here.

Thank you so much!


回答1:


In SwiftUI, Views are value types. They are only data that describe the things on screen. They can be created or destroyed or copied at any time. AVPlayer is a reference to a specific player object. You're assuming here that it will continue to exist, and there will only be one of them. That's not something that a SwiftUI View provides.

You need to move your AVPlayer outside of the View (into Model objects), and just bind UI actions to it.



来源:https://stackoverflow.com/questions/58792160/how-to-stream-remote-audio-in-ios-13-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!