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

playing a url link instead of a .mp3 file in swiftui

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

我的密码是

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

您可以像这样使用 AVPlayer 从 URL 流式传输资源。我还将 streaming/async 逻辑移动到 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()
                }
        }
    }
}