Dove Man
Dove Man

Reputation: 147

How to add mute/unmute button to browser audio player?

So I have my code here, and it works great. Only thing is there are no mute/unmute buttons and I have no idea how to add them.

<audio src="MUSIC URL" autoplay loop>
    <p>Your browser does not support the audio element </p>
</audio>

Upvotes: 1

Views: 3001

Answers (3)

Kristian
Kristian

Reputation: 1

Very easy:

<button onclick="document.getElementsByTagName('audio')[0].play();">Sound on</button>
<button onclick="document.getElementsByTagName('audio')[0].pause();">Sound off</button>
<audio autoplay preload="auto" loop src="your.mp3"></audio>

It is set on autoplay and loop, you can pause and resume by clicking the buttons. The best way to avoid diplaying the unsuitable browser player.

Upvotes: 0

Mohammad
Mohammad

Reputation: 21489

You should add controls attribute to audio tag.

If this attribute is present, the browser will offer controls to allow the user to control audio playback, including volume, seeking, and pause/resume playback. developer.mozilla

<audio src="http://audiomicro-dev.s3.amazonaws.com/preview/1030/caca5b5fcde48f9" controls>
  <p>Your browser does not support the audio element </p>
</audio>    

Upvotes: 1

mlegg
mlegg

Reputation: 832

I use this, get a play and pause button .png and use them. Then make a folder called audio and put the files in there for you music. I put the play and pause in a folder called images.

<style type="text/css">
audio {visibility: hidden; height: 0; width: 0; position: absolute; top: -300px; left: -300px;}
#pauseplay {float: right; width: 48px; height: 48px; overflow: hidden; cursor: pointer}
</style>

<audio controls loop>
<source src="**your website url here**/audio/waves.ogg" type="audio/ogg">
<source src="**your website url here**/audio/waves.mp3" type="audio/mpeg">
</audio>
<img id="pauseplay" src="**your website url here**/images/play.png" alt="button" title="Play/Pause">
<script type="text/javascript">
(function(){
	var playing = !!('ontouchstart' in window) || !!('ontouchstart' in document.documentElement) || !!window.ontouchstart || (!!window.Touch && !!window.Touch.length) || !!window.onmsgesturechange || (window.DocumentTouch && window.document instanceof window.DocumentTouch),
	snd = document.getElementsByTagName('audio')[0],
	ctrl = document.getElementById('pauseplay');
	playing = !playing;
	ctrl.title = playing? 'Pause' : 'Play';
	if(playing){snd.autoplay = false; ctrl.src = '**your website url** here/images/pause.png';}
	ctrl.addEventListener('click', function(){
		if(playing){
			snd.pause();
		} else {
			snd.play();
		}
		playing = !playing;
		ctrl.title = playing? 'Pause' : 'Play';
		ctrl.src = playing? '**your website url here**/images/pause.png' : '**your website url here**/images/play.png';
	}, false);
})();
</script>

If you want to see it live look at this site I made.

Upvotes: 1

Related Questions