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

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

问题描述

此代码使用 AVPlayer 仅适用于 Playground

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

当我尝试在我的物理设备上的 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天全站免登陆