Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...