1

I am making a web site and want to I want to load an MP3 file when my page refreshes, but somehow it won't play.

<body>
    <audio id="kofi" autoplay="autoplay">
        <source src="kofi.mp3" type="audio/mp3">
    </audio>

<script type="text/javascript">

window.onload = function(){
document.getElementById('kofi').play(); // On this line I get error "Uncaught (in promise) DOMException"
    }
</script>
<body>
ale10ander
  • 942
  • 5
  • 22
  • 42
Jimmy
  • 29
  • 4

1 Answers1

3

The play() / pause() functionality is using Promises, which is why it doesn't work how you expect. From this reference, I was able to make the below example:

<script>
  window.onload = function() {
    var song = document.getElementById('kofi');
    // This will allow us to play song later...
    song.load();
    fetchSongAndPlay();
  }

  function fetchSongAndPlay() {
    fetch('kofi.mp3')
    .then(response => response.blob())
    .then(blob => {
      song.srcObject = blob;
      return song.play();
    })
    .then(_ => {
      // Music playback started ;)
    })
    .catch(e => {
      // Music playback failed ;(
    })
  }
</script>
ale10ander
  • 942
  • 5
  • 22
  • 42
  • margin_collapsing.html:113 Fetch API cannot load file:///C:/Users/Administrator/Desktop/Folder/kofi.mp3. URL scheme must be "http" or "https" for CORS request. – Jimmy Jan 11 '19 at 15:30
  • @Jimmy you have to load your file on the same server. See this question. https://stackoverflow.com/questions/48728334/fetch-api-cannot-load-file-c-users-jack-desktop-books-h-book-site-public-api You can either run localhost server or move the file to an actual server. If you have any other issues, I'd recommend asking a new question about it. Hope this helps! – ale10ander Jan 11 '19 at 19:54