Toan Nguyen
Toan Nguyen

Reputation: 1103

Can't load audio file in javascript

Here is my code for load and play audio file .

<!DOCTYPE HTML>
<html lang="en-US">
<head>
     <meta charset="UTF-8">
     <title>Test audio</title>
</head>
<body>
<script type="text/javascript">
    window.onload = function() {
        var audio = new Audio("../../data/audio/background.ogg");
        audio.preload = "auto";

        audio.addEventListener('ended', function() {
            alert('ended');
        }, false);
        audio.addEventListener('canplaythrough', function() {
            audio.loop = true;
            audio.play();
        }, false);

        audio.onerror = function(event) {
            console.log(event.code);
        }

        audio.load();
    }
</script>
</body>
</html>

But I can't run it on Chrome (Firefox or IE 9 are oke) because when load audio file, I always get the error

error

How can I fix my code ?

Upvotes: 0

Views: 3140

Answers (2)

Kenjin
Kenjin

Reputation: 136

This works for me:

        var audioElement;
        audioElement = new Audio("");
        audioElement.addEventListener('ended', function() {
            this.currentTime = 0;
            this.play();
        }, false);

        document.body.appendChild(audioElement);
        audioElement.src = '../../data/audio/background.ogg';
        audioElement.id = "audioElement";

        audioElement.addEventListener('canplaythrough', function() {
            audioElement.play();
        }, false);

        audioElement.addEventListener('ended', function() {
            alert('ended');
        }, false);

        audioElement.onerror = function(event) {
           console.log(event.code);
        }

Upvotes: 1

Kinlan
Kinlan

Reputation: 16597

On Desktop Chrome you can do this automatically just in HTML without any Javascript.

<audio autoplay>
  <source src="test.ogg" type="audio/ogg">
  <source src="test.mp3" type="audio/mpeg">
  Sorry, no Audio support
</audio>

Your code in general should work. I just put it into http://jsbin.com/usific/1 and added my own audio file and I can see it downloading the entire file, it looks like your server is not accepting the request, or you have put in an incorrect URL.

Upvotes: 2

Related Questions