如何在iOS 13中流式传输远程音频? (SwiftUI) [英] How to stream remote audio in iOS 13? (SwiftUI)

查看:136
本文介绍了如何在iOS 13中流式传输远程音频? (SwiftUI)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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应用上运行它时,使用以下代码:

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

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

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.

非常感谢您!

推荐答案

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

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.

您需要将AVPlayer移到View之外(移到Model对象中),然后将UI动作绑定到该视图.

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

这篇关于如何在iOS 13中流式传输远程音频? (SwiftUI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆