How to play an audio file from an external url using Javascript?

22,117

Solution 1

Audio works correctly cross server without an additional issues, see the example below.

There can be a number of reasons why this wouldn't work:

  • Check the network tab to make sure the wav file is in the correct location.
  • Check the console for any warning messages of why it couldn't load.
  • Check this question/answer for additional debugging steps.
  • Post back with the URL that you're trying to grab from, or additional information about the request.

async function playAudio() {
  var audio = new Audio('https://file-examples.com/wp-content/uploads/2017/11/file_example_WAV_1MG.wav');  
  audio.type = 'audio/wav';

  try {
    await audio.play();
    console.log('Playing...');
  } catch (err) {
    console.log('Failed to play...' + err);
  }
}
<a href="#" onclick="playAudio()">Play Audio</a>

Solution 2

Try using the import function instead:

const playAudio = async () => {
    const importRes = await import("./path/to/audio.mp3"); // make sure the path is correct
    var audio = new Audio(importRes.default);
    try {
      await audio.play();
      console.log("Playing audio");
    } catch (err) {
      console.log("Failed to play, error: " + err);
    }
}

Solution 3

Instead use it in HTML 5 <audio> tag.

HTML 5 can play and control any audio format without using JavaScript.

Share:
22,117
Junior
Author by

Junior

Updated on July 05, 2022

Comments

  • Junior
    Junior almost 2 years

    I have an app (A) that makes an ajax request to a different app (B) to obtain a link for a wave sound file. Then, I want to use the link to play that sound file directly from my app (A).

    I tried to create a new audio tag but I am getting the following error in the console.

    In Chrome

    Failed to play....NotSupportedError: Failed to load because no supported source was found.

    In FireFox

    Failed to play....NotSupportedError: The media resource indicated by the src attribute or assigned media provider object was not suitable.

    Here is my callback method which is triggered after the ajax request is returned with the Link from my App (B).

    function playAudio(data) {
        if(!data || !data.DownloadUrl) {
            return;
        }
    
        var audio = new Audio(data.DownloadUrl);  
        audio.type = 'audio/wav';
    
        var playPromise = audio.play();
    
        if (playPromise !== undefined) {
            playPromise.then(function () {
                console.log('Playing....');
            }).catch(function (error) {
                console.log('Failed to play....' + error);
            });
        }
    }
    

    How can I successfully, get this wav file to play?

  • Junior
    Junior over 6 years
    This code is not working for me. When I click on "Play Audio" link nothing play.
  • Blue
    Blue over 6 years
    @MikeA What browser are you trying it in? Are you on the latest version?
  • Junior
    Junior over 6 years
    I am using FireFox 57.0.2 (64-bit) On another note, when creating a fiddle the code works file jsfiddle.net/o2gxgz9r/20484
  • Blue
    Blue over 6 years
    @MikeA Firefox didn't like the href="javascript:bleh, but I've updated my answer, and used onclick, and now it works.
  • Hernán Eche
    Hernán Eche over 5 years
    even with onclick, it doesn't work here but it works on jsfiddle as @MikeA said, why?
  • William Entriken
    William Entriken over 4 years
    Using latest macOS + Safari "Failed to play....NotSupportedError: The operation is not supported."
  • Blue
    Blue over 4 years
    @WilliamEntriken So you downvote me for lack of support for your audio file in macOS?
  • William Entriken
    William Entriken over 4 years
    Did not work for me in Chrome or Safari. I know web audio changes A LOT so my first guess is that this outdated.
  • Blue
    Blue over 4 years
    @WilliamEntriken I'm using chrome, and the reason it wasn't working earlier was due to the fact that it was hosted on a non-secure website, and the cross origin request failed as a result. When Stack Overflow switched to https, it broke this answer as a result. Switching the audio file to one hosted over https, is now allowing it to work.
  • gutterball
    gutterball over 2 years
    Only thing that worked for me.
  • timthedev07
    timthedev07 over 2 years
    I'm glad it helps!
  • Wisnu
    Wisnu over 2 years
    This also worked for me, but if using TS had to adjust a bit to be able to import audio. Thanks