Search code examples
jqueryaudiohtml5-audioaudio-streaming

how to make play/stop button for 2 radio stream on the same page?


I made 2 buttons for my radio streams, each one act like a PLAY/STOP button.

  1. play/stop for stream 1 (shoutcast or icecast)
  2. play/stop for stream 2 (shoutcast or icecast)

This is what i did, hen you press on both buttons, only 1 stream (funk) is played, the second one is not playing at all (disco)

can you help me please? thank you Tony

var player1 = document.querySelector('audio');
var player2 = document.querySelector('audio');
var playBtn1 = document.querySelector('#play-btn_funk');
var playBtn2 = document.querySelector('#play-btn_disco');


playBtn1.addEventListener('click', function() {
	if ( player1.paused ) {
		player1.play();
		playBtn1.src = 'img/stop_funk.png';
	} else {
		player1.pause();
		playBtn1.src = 'img/play_funk.png';
	}
});

playBtn2.addEventListener('click', function() {
	if ( player2.paused ) {
		player2.play();
		playBtn2.src = 'img/stop_disco.png';
	} else {
		player2.pause();
		playBtn2.src = 'img/play_disco.png';
	}
});
body {
	font-family:monospace;
	margin:0;
	line-height:1.45;
}

* {
	box-sizing:border-box;
}

#container_funk {
    float: left;
	width: 100px;
	margin:0 auto;
	padding: 1em;
	margin-top:5px;
}

#play-btn_funk {
	width:100px;
	cursor: pointer;
	display:inline-block;
}

#container_disco {
	position:relative;
    float:left;
	width: 100px;
	margin:0 auto;
	padding: 1em;
	margin-top:5px;
}

#play-btn_disco {
	width:100px;
	cursor: pointer;
	display:inline-block;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
<title>HTML5 Audio Player</title>
</head>
<body>
	<div id="container_funk">
		<audio id="funk">
		<source type="audio/mpeg" src="http://163.172.29.170:8000/;"/>
		</audio>
		<img id="play-btn_funk" src="img/play_funk.png" />
		</div>
<div id="container_disco">
  <audio id="disco">
		<source type="audio/mpeg" src="http://163.172.29.170:8080/;"/>
	</audio>
	<img id="play-btn_disco" src="img/play_disco.png" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script type="text/javascript" src="js/audio.js"></script></div>
</body>
</html>


Solution

  • Your code looks good already. It just needs a minor tweak.

    The player1 and player2 variables reference exactly the same <audio/> element. document.querySelector() will search the DOM for the first matching element which is #funk in your case. Just replace the first two lines with an explicit query for each player.

    var player1 = document.querySelector('#funk');
    var player2 = document.querySelector('#disco');