0

What I'm trying to do is have it so that when the page loads have it play highpitchsound.wav (or .mp3) for x amount of seconds the user defines in an alertbox on page load.

In the alertbox there's a textbox, and a button "Confirm". The default text is 5 for 5s, or 5000 for 5000ms.

I've used intervals with jquery before, messed with audio in html5 a couple times here, and there, not sure how to combine the two for this, and also don't know how I'd make a custom alertbox onload.

<html>
<head>
<title>Audio Play Interval</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {

});
</script>
</head>
<body>
    <audio autoplay="true">
        <source src="sounds/highpitchsound.mp3" type="audio/mpeg" />
        <source src="sounds/highpitchsound.wav" type="audio/wav" />
        <source src="sounds/highpitchsound.ogg" type="audio/ogg" />
        Your browser does not support the audio element.
    </audio>
</body>
</html>
Michael Schwartz
  • 8,153
  • 14
  • 81
  • 144
  • 2
    Just as a side note, it may be better to ask for seconds from the user rather than milliseconds, and then do the conversion yourself - the general populace doesn't do milliseconds well! – ahren Aug 14 '12 at 06:07

1 Answers1

5

Understanding

You can achieve this by referencing the audio element specifically as an object. Because jquery does not extend HTMLAudioElement yet you have to specifically refer to the first record within the jquery object for the audio element.

You can then simply reference any of the functions such as .play(), .pause() or .load() from then on.

You can do this simply like so:

setInterval(function() { $('audio')[0].play(); },1000);

Breaking this down

  • We use setInterval(a(),b) to run the function a() every b amount of milliseconds

  • reference the audio html object in the dom $('audio') and then select the HTMLAudioElement object within that to interact with it ($('audio')[0])

  • then we can simply use any of the functions within that ( i.e .play() )

Solution

Now, in order to achieve what you want you can do this,

Javascript:

startplaying(parseInt(prompt('in milliseconds, set an interval!')));

function startplaying(time) {
    var run = setInterval(function() { $('audio')[0].play(); }, time);
}

this first prompts the user to write in a time and then executes the function with the time set out by the user with a touch of validation.

Michael Zaporozhets
  • 23,588
  • 3
  • 30
  • 47