Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 944
Junior Avatar asked Dec 19 '17 19:12

Junior


1 Answers

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

like image 171
timthedev07 Avatar answered Nov 14 '22 15:11

timthedev07