在 swiftui 中播放 url 链接而不是 .mp3 文件

问题描述 投票:0回答:2

我使用 AVFoundation 制作了一个简单的快速音频视图。该代码适用于下载的文件,但我不希望应用程序的大小非常大。如果我可以从 URL 链接播放它,有可能吗?

我的密码是

import SwiftUI
import AVFoundation
import AVFAudio

struct AudioTest: View {
    
    @State var song1 = false
    
    var body: some View {
        Image(systemName: song1 ? "pause.circle.fill": "play.circle.fill")
            .font(.system(size: 25))
            .padding(.trailing)
            .onTapGesture {
                playSound(sound: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3", type: "mp3")
                song1.toggle()
                
                if song1{
                    
                    audioPlayer1?.play()
                } else {
                    audioPlayer1?.pause()
                    
                }
        }
    }
}

struct AudioTest_Previews: PreviewProvider {
    static var previews: some View {
        AudioTest()
    }
}

var audioPlayer1: AVAudioPlayer?

func playSound1(sound: String, type:String){
    if let path = Bundle.main.path(forResource: sound, ofType: type) {
        do{
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
            //audioPlayer?.numberOfLoops = -1
            
        }catch{
            print(error)
        }
    }
}

xcode swiftui avfoundation xcode12
2个回答
4
投票

您可以使用

AVPlayer
从这样的 URL 流式传输资源。我还将流式传输/异步逻辑移动到
ObservableObject
:


class SoundManager : ObservableObject {
    var audioPlayer: AVPlayer?

    func playSound(sound: String){
        if let url = URL(string: sound) {
            self.audioPlayer = AVPlayer(url: url)
        }
    }
}

struct ContentView: View {
    @State var song1 = false
    @StateObject private var soundManager = SoundManager()
    
    var body: some View {
        Image(systemName: song1 ? "pause.circle.fill": "play.circle.fill")
            .font(.system(size: 25))
            .padding(.trailing)
            .onTapGesture {
                soundManager.playSound(sound: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")
                song1.toggle()
                
                if song1{
                    soundManager.audioPlayer?.play()
                } else {
                    soundManager.audioPlayer?.pause()
                }
        }
    }
}

0
投票

使用 AVPlayer 导入 SwiftUI 导入 AVFoundation

结构内容视图:视图{ @State var player: AVPlayer?

var body: some View {
    Button("Play Audio") {
        guard let url = URL(string: "https://example.com/audio.mp3") else { return }
        let playerItem = AVPlayerItem(url: url)
        self.player = AVPlayer(playerItem: playerItem)
        self.player?.play()
    }
}

}

© www.soinside.com 2019 - 2024. All rights reserved.