Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...