skip to Main Content

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:

https://firebasestorage.googleapis.com:443/v0/b/unified-45b5c.appspot.com/o/AudioMessage%2F5%2B8_5_Audio_07-09-20224:07:30.m4a?alt=media&token=af3aabce-46bd-4d55-a7ca-30623eaf1817

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


  1. 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:

    Declaration
    init(contentsOf url: URL) throws
    Parameters
    url
    A URL that identifies the local audio file to play
    

    You’ll need to download the data to a local file before playing it, or use a method that supports streaming audio playback.

    Login or Signup to reply.
  2. 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:

    Use an instance of AVPlayer to play local and remote file-based media, such as QuickTime movies and MP3 audio files, as well as audiovisual media served using HTTP Live Streaming.

    let player = AVPlayer(playerItem: item) 
    let audio = AVPlayerItem(url: url)
    player.play()
    

    Note that you can keep an instance of the player to play multiple items

    See this answer for detailed comparison between the two

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search