I know this is a duplicate question but I did not find any solution that works for me.
I am using AVAudioPlayer to play an audio with the url which I am getting from Firebase. The url I get from Firebase is:
if I open this url on google chrome it gives me my audio. But when I try it using AVAudioPlayer it gives me the following error:
The operation couldn’t be completed. (OSStatus error 2003334207.)
This is what I am doing:
Button {
vm.startPlaying(url: audioURL ?? URL(fileURLWithPath: ""))
} label: {
Image(systemName: startAudio ? "pause.fill" : "play.fill")
.foregroundColor(.black)
.padding()
.background(
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.gray)
.frame(width: 100)
)
}
And the function startPlaying():
func startPlaying(url : URL) {
do {
audioPlayer = try AVAudioPlayer(contentsOf : url)
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
Helper.shared.printDebug("Playing Failed")
Helper.shared.printDebug(error.localizedDescription) // error: The operation couldn’t be completed. (OSStatus error 2003334207.)
}
}
2
Answers
The initializer you are using for AVAudioPlayer expect an URL to a local file. You can’t pass it a URL to a file on a remote server. To quote the docs:
You’ll need to download the data to a local file before playing it, or use a method that supports streaming audio playback.
Duncan’s solution works if you want to download the item first, and then play it. If you want more like a streaming experience, you can use AVPlayer, which is built to allow playing remote files, and helps with streaming:
Note that you can keep an instance of the player to play multiple items
See this answer for detailed comparison between the two