Unfortunately, I believe the .play() method is part of the DOM and not a jQuery function. You can accomplish it in couple of ways:
- $(tone)[0].play(); -- as answered by jremi. The only caveat is that you must use index of zero. I don't this will work: $(tone)[1].play();
- $(tone).get(0).play();
- $(tone).trigger("play")
Try it here:
jQuery:
$( document ).ready(function() {
function playSound(){
var pattern = [],
tone;
pattern.push(Math.floor(Math.random() * 4));
tone = "#sound" + pattern[0];
//$(tone).trigger('play'); //uncomment to play
//$(tone).get(0).play(); //uncomment to play
$(tone)[0].play(); //comment to turn off
}
$("#button").click(playSound);
});HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <audio id="sound0" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio> <audio id="sound1" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio> <audio id="sound2" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio> <audio id="sound3" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio> <button id="button">Click To Play</button>
Ещё вариант
jQuery:
var sounds = [];
// Return the full list of URLs in random order
function getSounds() {
return [
// so tinny...
'http://www.freesound.org/data/previews/169/169198_1587259-lq.mp3',
'http://www.freesound.org/data/previews/169/169196_1587259-lq.mp3',
'http://www.freesound.org/data/previews/169/169203_1587259-lq.mp3',
'http://www.freesound.org/data/previews/169/169202_1587259-lq.mp3',
'http://www.freesound.org/data/previews/169/169201_1587259-lq.mp3'
].sort(function () {
// http://stackoverflow.com/a/18650169/283078
return (.5 - Math.random());
});
}
// Play the next sound
function playSound() {
if (!sounds.length) {
// Get the list of sounds (random order)
sounds = getSounds();
}
// Pops a URL every time, ensuring all are played exactly once
$("#element").html(
'<embed src="' + sounds.pop() +
'" hidden="true" autostart="true" />'
);
// Once all the URLs have been popped, the array is repopulated
}
$('#test').click(playSound);HTML:
<button id=test>Click to play</button> <div id=element></div>