user5902649
user5902649

Reputation:

Play one HTML audio file at a time with Javascript/jQuery

In my page, every keyboard key triggers an audio file. For letters A to Z, the corresponding audio file is played, for every other key (except for ESC) a random one of the 26 audio files is played instead. If I press for example A and B, both audio files will play at the same time, but I would like just for one file to be played at a time. How would I achieve this?

function keyDown(event) {
    var key = event.keyCode, sound, randomSound;
    if (key === 27) {
        //Play exit audio file, remove event listener, exit...
    } else if (key >= 65 && key <= 90) {
        sound = document.getElementById(key);
        sound.play();
    } else {
        randomSound = getRandomInt(65, 90);
        sound = document.getElementById(randomSound);
        sound.play();
    }

    window.onload = function() {
    window.addEventListener("keydown", keyDown);
};

Edit: I would like the audio file to play until the end before the user can press another key and trigger another file. I apologize for not making this clear before.

Upvotes: 3

Views: 2812

Answers (1)

Tennyson H
Tennyson H

Reputation: 1716

The reason this is happening is because each <audio> element plays on it's own channel. To make it play one at a time, you should just be using one Audio object.

To achieve this, you should just be using one Audio object. Like so:

var audio = new Audio();

...

if (!audio.paused) audio.pause();
if (key >= 65 && key <= 90) {
    audio.src = document.getElementById(key).src; /* set audio.src to URL of individual audio element */
    audio.play();
} else {
    randomSound = getRandomInt(65, 66);
    audio.src = document.getElementById(randomSound).src; /* set audio.src to URL of individual audio element */
    audio.play();
}

EDIT

To answer your revised question, you would simply do something like this

var audio = new Audio();

function keyDown(event) {
    if (!audio.paused) // if audio hasn't ended, don't replace it.
        return; 

    var key = event.keyCode, sound, randomSound;
    if (key === 27) {
        //Play exit audio file, remove event listener, exit...
    } else if (key >= 65 && key <= 90) {
        audio.src = document.getElementById(key).src;
        audio.play();
    } else {
        randomSound = getRandomInt(65, 90);
        audio = document.getElementById(randomSound).src;
        audio.play();
    }

    window.onload = function() {
    window.addEventListener("keydown", keyDown);
};

Upvotes: 4

Related Questions