Home > Software engineering >  I want to pause current playing audio when another audio start
I want to pause current playing audio when another audio start

Time:02-23

I have an web application when click the artist image that plays audio files. I'm pretty new to this. I found a few solutions on the internet, but I couldn't do it. I want to pause current playing audio when another audio start.but it continues to play in the background , but what I want is to pause and continuing playing from that point forward. So far, I could not make that change.

function switchCase(key){
    switch (key) {
        case 'mozart-img':
            var audio = new Audio("sounds/mozart.mp3")
            audio.play();
            break;
        case 'beethoven-img':
            var audio = new Audio("sounds/beethoven.mp3")
            audio.play();
            break;
        case 'chopin-img':
            var audio = new Audio("sounds/chopin.mp3")
            audio.play();
            break;
        case 'schumann-img':
            var audio = new Audio("sounds/schumann.mp3")
            audio.play();
            break;                
        default:
            break;
    }
}

CodePudding user response:

Using an IIFE here so no globals will be required (other than the function switchCase which you have already anyway)

const switchCase = (function() {
    let playing;
    function stop() {
        if (playing) {
            playing.removeEventListener('ended', stop); //*
            playing.pause();
            playing = null;
        }
    }
    return function (key){
        stop();
        switch (key) {
            case 'mozart-img':
                playing = new Audio("sounds/mozart.mp3");
                break;
            case 'beethoven-img':
                playing = new Audio("sounds/beethoven.mp3");
                break;
            case 'chopin-img':
                playing = new Audio("sounds/chopin.mp3");
                break;
            case 'schumann-img':
                playing = new Audio("sounds/schumann.mp3");
                break;                
            default:
                break;
        }
        playing.play();
        playing.addEventListener('ended', stop); //*
    };
})();

So, playing holds the currently playing audio object - before creating a new one, simply stop the currently playing one (if it exists)

Added "ended" event handler - probably overkill, but just remove the lines with addEventListener and removeEventListener (marked with //* ) to get rid of probably redundant event handling

  • Related