1

I am trying to play a sound in Safari on a special event. This is what I am doing

<html>
    <head>
        <in a js file>
            if(event)
                document.getElementById('sound').play();
        </in a js file>
    </head>
    <body>    
        <audio id="sound" src="pling.mp3"></audio> 
    </body>
</html>

The sound pling.mp3 is in the the same folder as the html file.

The result in Safari developer console is: TypeError: Result of expression 'document.getElementById('sound').play' [undefined] is not a function.

What am I doing wrong? Isn't this the way it is supposed to work?

Joost Baaij
  • 7,188
  • 2
  • 30
  • 33
TDH
  • 25
  • 6

2 Answers2

3

Try the following:

document.getElementById('sound')[0].play();
Ian Devlin
  • 17,608
  • 4
  • 53
  • 69
-1

I would use the Audio API, as explained here, to play sound effects after certain events. In my opinion the audio tag is more suited for songs can be played, stopped and controlled via the UI. If you do use audio tags, you must pause and rewind before it can be played again. You can use this script which does that automatically.

If you want to play audio for example on hover events, do something like this in jQuery:

// iterate through the elements that must have audio applied on hover
$('.audio_effect').each(function() {
  $(this).on('mouseover', function() {
    new Audio('path-to-audiofile.mp3').play();
  });
});

Since you can't play an Audio element again without resetting its internal pointer, the easiest course of action is to just create the element fresh on every hover, like I am doing above.

Community
  • 1
  • 1
Joost Baaij
  • 7,188
  • 2
  • 30
  • 33
  • Update: apparently IE9 and lower do not support the `new Audio()` constructor. The most cross-platform solution is to create `audio` elements using document.createElement(). – Joost Baaij Jun 04 '12 at 12:07
  • Your first statement is incorrect, as you can of course do this with the audio element and the Media API, as that's what it's there for. – Ian Devlin Jun 04 '12 at 12:20
  • 1
    Hi Ian, thanks so much for the downvote. I do understand that the sound can play once by using an `audio` tag and the code you provided. But in order to play the sound again you must rewind it. Your answer will do no good when the event fires again. I will update my answer to reflect that. – Joost Baaij Jun 05 '12 at 06:41