Saturday, 7 September 2013

javascript: emulate 'stop' functionality in looping context with audio playback

javascript: emulate 'stop' functionality in looping context with audio
playback

the code below creates a little program to compose music based on
structuring randomly chosen tones from arrays. The only problem is, once
you start it going, the only way to make it stop it is to
refresh/redirect/close the browser.
For the moment I am only interested in stopping playback (though later I
would like to attempt the more complicated maneuver of a pause/resume
function.) I imagine that this would involve the clearTimeout method, but
haven't quite figured out how to apply it in this context.
Thanks for your code offerings or suggestions!
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<style>
body {background: #999;}
</style>
<script type="text/javascript">
function getRandInt (min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(o)
{
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x
= o[--i], o[i] = o[j], o[j] = x);
return o;
}
function setup(uniqueId, toneArray, totalTones, startTime, endTime)
{
function getDelays()
{
var return_array = new Array();
for (var i = 0; i < totalTones; i++)
{
var r = getRandInt(startTime, endTime);
var delay = r * 1000;
return_array.push(delay);
}
return return_array;
}
var delays = new Array();
delays = getDelays();
for (var i=1; i <= totalTones; i++)
{
shuffle (toneArray);
var idBase = uniqueId;
var samplepick = toneArray[0];
$("<audio controls id='" + idBase + "_" + i + "'><source
src='" + samplepick + "'
type='audio/ogg'></source></audio>").appendTo("body");
}
$("#start").click(function()
{
var idBase = uniqueId;
for(var i = 0; i < totalTones; i++)
{
var id = idBase + "_" + ((i + 1) );
window.setTimeout ("document.getElementById('" + id +
"').play()", delays[i]);
}
});
}
$(document).ready(function()
{
var majThird = new Array("tone0.ogg", "tone4.ogg");
var lydScale = new Array("tone0.ogg", "tone2.ogg", "tone4.ogg",
"tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg",
"tone12.ogg");
var octave = new Array("tone0.ogg", "tone12.ogg");
setup ("first", majThird, 4, 0, 10);
setup ("second", lydScale, 8, 20, 30);
setup ("third", octave, 4, 40, 50);
});
</script>
</head>
<body>
<button id="start">Start</button>
<br><br>
</body>
</html>

No comments:

Post a Comment