56

I'm getting DOMException: Failed to load because no supported source was found in video.play(); line. I'm getting this issue only after adding video.setAttribute('crossorigin', 'anonymous'); I'm developing app in mobile so for cross origin i need to add this line. After update of chrome 50 version i'm getting this issue before that it works fine.

<!DOCTYPE html>
    <html>
    <head> 
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    </head> 
    <body>  
    <script>     
     var video = document.createElement( 'video' ); 

     video.id = 'video';    
     video.type = ' video/mp4; codecs="theora, vorbis" ';   
     video.src = "http://abcde.com/img/videos/what_is_design_thinking.mp4"; 
     video.volume = .1; 
     video.setAttribute('crossorigin', 'anonymous');    
     video.load(); // must call after setting/changing source   

     $('body').html(video);
     video.play();  

     var canvas = document.createElement('canvas');
     var ctx = canvas.getContext('2d');

     $('body').append(canvas);

     video.addEventListener('play', function() {
       var $this = this; //cache
       (function loop() {
       if (!$this.paused && !$this.ended) {
       ctx.drawImage($this, 0, 0);
       setTimeout(loop, 1000 / 30); // drawing at 30fps
       }
       })();
      }, 0);

    </script>
    </body> 
    </html>
3

17 Answers 17

39

I've had the same issue in VueJS. The thing that worked for me was to replace:

const audio = new Audio(required('../assets/sound.mp3')) 
audio.play()

with:

import sound from '../assets/sound.mp3'
const audio = new Audio(sound)
audio.play()
5
  • This worked great, thank you!
    – John P
    Commented Oct 6, 2021 at 21:31
  • 4
    Working in Vue JS 3 and worked like a charm! Thank you very much... Commented Dec 8, 2021 at 16:02
  • This helped, but now it wont pause the audio, any solutions for that Commented Apr 15, 2022 at 7:50
  • This works but what if I need sound to be dynamic? import' and 'export' may only appear at the top level
    – etayluz
    Commented May 6, 2022 at 14:06
  • Have a look at dynamic imports developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented May 19, 2022 at 10:50
36

This problem occurs in newer Chrome/Chromium browsers starting from v50

From HTMLMediaElement.play() Returns a Promise by Google Developers:

Automatically playing audio and video on the web is a powerful capability, and one that’s subject to different restrictions on different platforms. Today, most desktop browsers will always allow web pages to begin <video> or <audio> playback via JavaScript without user interaction. Most mobile browsers, however, require an explicit user gesture before JavaScript-initiated playback can occur. This helps ensure that mobile users, many of whom pay for bandwidth or who might be in a public environment, don’t accidentally start downloading and playing media without explicitly interacting with the page.

It’s historically been difficult to determine whether user interaction is required to start playback, and to detect the failures that happen when (automatic) playback is attempted and fails. Various workarounds exist, but are less than ideal. An improvement to the underlying play() method to address this uncertainty is long overdue, and this has now made it to the web platform, with an initial implementation in Chrome 50.

A play() call on an a <video> or <audio> element now returns a Promise. If playback succeeds, the Promise is fulfilled, and if playback fails, the Promise is rejected along with an error message explaining the failure. This lets you write intuitive code like the following:

var playPromise = document.querySelector('video').play();

// In browsers that don’t yet support this functionality,
// playPromise won’t be defined.
if (playPromise !== undefined) {
  playPromise.then(function() {
    // Automatic playback started!
  }).catch(function(error) {
    // Automatic playback failed.
    // Show a UI element to let the user manually start playback.
  });
}

In addition to detecting whether the play() method was successful, the new Promise-based interface allows you to determine when the play() method succeeded. There are contexts in which a web browser may decide to delay the start of playback—for instance, desktop Chrome will not begin playback of a <video> until the tab is visible. The Promise won’t fulfill until playback has actually started, meaning the code inside the then() will not execute until the media is playing. Previous methods of determining if play() is successful, such as waiting a set amount of time for a playing event and assuming failure if it doesn’t fire, are susceptible to false negatives in delayed-playback scenarios.

Credits: Failed to load because no supported source was found. when playing HTML5 audio element

3
  • 24
    The addition of promises to play() has nothing to do with the DOMException error in the question. It's a CORS issue.
    – Michael F
    Commented Apr 16, 2017 at 7:11
  • 3
    as @MichaelFranzl mentioned above, error is not because of promise, error may be also occurred when the audio is not there on the url provided as source Commented May 3, 2021 at 2:14
  • I returned a JSON instead of audio blob and got this error.
    – kiranvj
    Commented Nov 30, 2022 at 12:15
6

I had the same error and it turned out to be a CORS issue.

Instead of

video.setAttribute('crossorigin', 'anonymous');  

try the more explicit way:

video.crossOrigin = 'anonymous';

And make sure that the server response has the header Access-Control-Allow-Origin: *. Or instead of the asterisk wildcard, specify the domain of the website that is allowed to access the video from the server.

2
  • 7
    Please note that in the first version you are setting 'crossorigin', and in the second 'crossOrigin', with a capital O in Origin. That might account for the difference, rather than the different methods. Commented May 8, 2017 at 15:16
  • 2
    @PerQuestedAronsson I think the attribute name is supposed to be all small case, what Michael has seems correct. developer.mozilla.org/en-US/docs/Web/HTML/Element/video
    – Jun
    Commented Jun 19, 2018 at 23:30
5

I had the same problem with an mp3 file. My solution was to add content to the html through javascript.

Example of HTML where i'm going to put the file to be played.

<span id="audio"></span>

And in javascript:

$('#audio').html('<audio autoplay><source src="audio/ding.mp3"></audio>');

This will play the audio, assuming its the same for video.

Hope it helps

3

I had the same problem, but the cause was the file name contained a '#'.

Apparently, if the file name contains a '#' I would get net::ERR_FILE_NOT_FOUND if setting the src directly to the string

document.getElementById('audio').src = '../path/x#y.webm';
console.log(document.getElementById('audio').src); // C:\Users\x\y\z\path\x#y.webm

But would get a DOMException: The element has no supported sources. when using node's path.resolve even though the html element's src attribute would be the same

document.getElementById('audio').src = path.resolve('path', 'x#y.webm');
console.log(document.getElementById('audio').src); // C:\Users\x\y\z\path\x#y.webm

Renaming the file name to x-y.webm resolved the issue.

This was using electron on windows, it may not be the case on other os's or on web apps.

1
  • Is there a workaround for this particular issue other than renaming the file? Thanks
    – Megan
    Commented Apr 18, 2019 at 1:56
2

A solution could be to put the audio files in a public folder.

In a react app you might automatically have a public folder. Issues with loading the audio file could be the browser interpreting that path relative to the current URL. It is good to put static files in the public folder.

I had this problem when I would try to reference an audio file like this:

const voiceButtonClicked = () => {
    var audio = new Audio('./audios/test.mp3')
    audio.play()
  }

It would give the error Failed to load because no supported source was found. I had the audio files in the src folder. After moving the audios to the public folder it worked.

When importing the test.mp3 at the top it worked too. Might have something to do with the javascript being processed through the import. But it is not efficient to import all audio files at the time in some cases.

2
  • In React when you put the mp3 or mp4 files outside the src folder you get an error about not being able to Import. However, I've found it to work using videos in the src. For me I had run into this issue using the Git LFS command for large files and due to conflict the video file became corrupted. Commented Nov 1, 2023 at 7:11
  • @JeremyThompson I do not import the mp3 when it is in the public folder. I just reference the file path. If you had an audios folder in the public folder it would look like "/audios/test.mp3" Commented Nov 30, 2023 at 16:29
0

If you are having this error and none of the answers above apply " DOMException: Failed to load because no supported source was found " could mean you opened your code without opening the file containing the audio or video file you wish to play

0

This same error can crop up if you are serving your app/site from localhost (eg during development) with http, and have the files stored in a Cache that you are using match() to determine if the file is in the Cache (or not). In my case, I had to add an option to set 'ignoreVary' to true on the call to match(), either on the call you make explicitly:

await myCache.match(filename, {ignoreVary: true}) // ignoreVary for localhost

or if using workbox in a service worker:

workbox.strategies.cacheOnly({
  cacheName: myCacheName,
  matchOptions: {
    ignoreVary: true, // <- this is the important bit
  },
  plugins: [
    /* bla bla */
  ]
})

Refs: https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage/match https://github.com/GoogleChrome/workbox/issues/1550

0

I had this same error, and the issue was that the file itself was not set to public, therefore there was no source loading for the file.

0

I'm just learning and made a DrumKit page using Javascript, when I open in live server (Visual Studio Code) it worked perfect, but when upload to github there was no sound... I was watching and reading and find this:

I was using this code enter image description here

and the error was: "Failed to load because no supported source was found".

The way to make it work was so easy like add a dot before / enter image description here

I hope my first contribution help someone with this errors.

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. Commented Dec 4, 2022 at 2:05
0

This may help some people, but sometimes this means you have given a nonexistent path to a file. For example:

const Audio = new Audio("/music.mp3")

isn't a file in the root directory, so Javascript throws an error. An easy fix is

const Audio = new Audio("./music.mp3")

, which will check the current directory instead of the root directory.

REMEMBER:

./ = Current directory
/ = Root directory
../ = Parent directory

0

In my case it was just an extra slash at the end of my URL. The fact is that I used a CDN for sounds and out of habit added a slash "http://path/name.mp3/". I just removed it ("http://path/name.mp3") and now it works. Maybe it will be useful for someone.

0

As an addition to answers above - you would want to add some additional features for audio play as follows:

import SoundNewMessage from 'yourPathHere/sound-new-message.mp3';

const newMessageAudio = new Audio(SoundNewMessage);

export const playMessageNotificationAudio = () => {
  // Do not overlap sounds if there are multiple concurrent notifications
  if (newMessageAudio.paused) {
    // DOMException: play() failed because the user didn't interact with the document first.
    // eslint-disable-next-line no-console
    newMessageAudio.play().catch(console.warn);
  }
};


0

In my case this error was triggered when trying to play an H.265 encoded video on mobile. On desktop there was no error.

So I fixed this by re-encoding my video with H.264 codec:

ffmpeg -i input.mp4 -vcodec libx264 -acodec aac output.mp4

0

In my case it's because I was trying to play the audio whilst the stream was still recording, hence the error and conflict. Make sure you stop the stream first before playing anything. You can use the function below to stop and recordings before playing.

function stopRecording() {
    if (captureIntervalId) {
        clearInterval(captureIntervalId);
        captureIntervalId = null;
    }
    if (stream) {
        let tracks = stream.getTracks();
        tracks.forEach(track => track.stop());
        stream = null;
    }
}
-3
  <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>append demo</title>
  <style>
  p {
    background: yellow;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>I would like to say: </p>

<script>
 var video = document.createElement( 'video' ); 

     video.id = 'video';    
     video.type = ' video/mp4; codecs="theora, vorbis" ';   
     video.src = "http://www.w3schools.com/html/mov_bbb.mp4"; 

    // $('body').html(video);
     video.play();  
     video.addEventListener('play', function() {
       var $this = this; //cache
       (function loop() {
       if (!$this.paused && !$this.ended) {      
       setTimeout(loop, 1000 / 30); // drawing at 30fps
       }
       })();
      }, 0);
$( "p" ).append( video );
</script>

</body>
</html>
1
  • 3
    you should add more detail to your answer where you point out the mistake in the original post and then add the code Commented Dec 7, 2017 at 3:35
-4

I had this problem in a NodeJS / Electron app. It turned out to be the path to the audio file was wrong.

Not the answer you're looking for? Browse other questions tagged or ask your own question.