Search code examples
javascriptjqueryaudiojplayeraudio-player

Start one of the audio files muted when playing two at the same time


I have two audio files starting at the same time, and a toggle button to switch between the two by muting the other.

Everything is as I intended it to be but when I press play, I want audio2 to start muted. Right now you can hear them both in the same time.

https://jsfiddle.net/9z1dfm4p/

var audio1 = document.getElementById('audio1');
var audio2 = document.getElementById('audio2');
var button1 = document.getElementById('button1');
var isPlaying = false;
var muteToggle = true;
var play = function() {
  if (!isPlaying) {
    button1.innerHTML = 'Pause';
    audio1.play(); // this stream will immediately stop when the next line is run on iOS
    audio2.play(); // this will stop audio1 on iOS
    isPlaying = true;
  } else {
    button1.innerHTML = 'Play';
    audio1.pause(); // this stream will immediately stop when the next line is run on iOS
    audio2.pause(); // this will stop audio1 on iOS
    isPlaying = false;
  }
}

var mute = function() {
  if (muteToggle) {
    muteToggle = false;
    audio1.muted = true;
    audio2.muted = false;
  } else {
    muteToggle = true;
    audio2.muted = true;
    audio1.muted = false;
  }
}
<audio id="audio1">
    <source src="http://jplayer.org/audio/mp3/Miaow-07-Bubble.mp3" type="audio/mpeg" />
    </audio><br />
<audio id="audio2">
    <source src="https://allthingsaudio.wikispaces.com/file/view/Shuffle%20for%20K.M.mp3/139190697/Shuffle%20for%20K.M.mp3" type="audio/mpeg"/>
    </audio><br />
<button onclick="play();" id="button1">Play</button><br />
<button onclick="mute();" id="button2">Toggle</button><br />


Solution

  • You could set the second <audio> to be muted from the beginning.

    <audio id="audio2" muted="true">
    

    https://jsfiddle.net/9z1dfm4p/2/

    EDIT: Cleaned up code and better display of what song is playing.

    https://jsfiddle.net/9z1dfm4p/7/