How to control multiple audio player with JavaScript? - javascript

I create two audio players on the same web page.
<audio id="player0">
<button id="play0" /><button id="forward0" />
<button id="backward0" /></audio> <audio id="player1">
<button id="play1" />
<button id="forward1" /><button id="backward1" />
</audio>
But when I click "play0", both of them play. I think the problem is I'm binding the eventListener to one playbtn. Can someone tell me how to unbind the eventListener, so I can play just one at a time?
var index = 0;
var playbtn = document.getElementById("play-images-"+index);
var playbtn.addEventListener("click", playPause, false);
index++;
function playPause(){
playbtn = document.getElementById("play"+index);
if(!audio.paused && !audio.ended){
audio.pause();
}else{
audio.play();
}
}

This should be close to what you need...
HTML
<audio id="player0">
<button id="play0" />
<button id="forward0" />
<button id="backward0" />
</audio>
<audio id="player1">
<button id="play1" />
<button id="forward1" /><button id="backward1" />
</audio>
JavaScript
// init page when window loads
window.addEventListener('load', initPage, false);
function initPage() {
// add click event to play buttons
var btnColl = document.getElementsByTagName('button');
for (var i = 0; i < btnColl.length; i++) {
if (btnColl[i].id.indexOf('play')> -1) {
btnColl[i].addEventListener('click', playPause, false);
}
}
}
function playPause(sender) {
// get audio player based on button id
var audioPlayer = document.getElementById(sender.srcElement.id.replace('play', 'player'));
if(!audioPlayer.paused && !audioPlayer.ended){
audioPlayer.pause();
}else{
audioPlayer.play();
}
}

Related

How to use same logic for multiple audioplayers on my page

I want to change playback speed for number of audio clips on the same HTML page.
The JS code for changing the speed goes like this:
var vid = document.getElementById("myAudio");
function getPlaySpeed() {
alert(vid.playbackRate);
}
function setPlaySpeed10() {
vid.playbackRate = 1.0;
}
function setPlaySpeed09() {
vid.playbackRate = 0.9;
}
function setPlaySpeed08() {
vid.playbackRate = 0.8;
}
And HTML for audio is this:
<audio id="myAudio" controls src="/home/../../../1-001.mp3"></audio>
<button onclick="getPlaySpeed()" type="button">What's the speed</button>
<button onclick="setPlaySpeed10()" type="button">1</button>
<button onclick="setPlaySpeed09()" type="button">0.9</button>
<button onclick="setPlaySpeed08()" type="button">0.8</button>
<audio id="myAudio" controls src="/home/../../../1-002.mp3"></audio>
<button onclick="getPlaySpeed()" type="button">What's the speed</button>
<button onclick="setPlaySpeed10()" type="button">1</button>
<button onclick="setPlaySpeed09()" type="button">0.9</button>
<button onclick="setPlaySpeed08()" type="button">0.8</button>
So the speed actually changes only for the first element.
I did change the id for the second element to myAudio1 and duplicated the JS code with the myAudio1 and this way both of them work, obviously :) but there should be better way!
Please help :)
Passing the element id as a parameter in your functions will eliminate the need to duplicate your functions. The same thing can be applied to the speed as well.
function getPlaySpeed(elementId) {
var vid = document.getElementById(elementId);
alert(vid.playbackRate);
}
function setPlaySpeed(elementId, speed) {
var vid = document.getElementById(elementId);
vid.playbackRate = speed;
}
<audio id="myAudio-001" controls src="https://audionautix.com/Music/AshesOfAnEmpire.mp3"></audio>
<button onclick="getPlaySpeed('myAudio-001')" type="button">What's the speed</button>
<button onclick="setPlaySpeed('myAudio-001', 1.0)" type="button">1</button>
<button onclick="setPlaySpeed('myAudio-001', 0.9)" type="button">0.9</button>
<button onclick="setPlaySpeed('myAudio-001', 0.8)" type="button">0.8</button>
<audio id="myAudio-002" controls src="https://audionautix.com/Music/Assasins.mp3"></audio>
<button onclick="getPlaySpeed('myAudio-002')" type="button">What's the speed</button>
<button onclick="setPlaySpeed('myAudio-002', 1.0)" type="button">1</button>
<button onclick="setPlaySpeed('myAudio-002', 0.9)" type="button">0.9</button>
<button onclick="setPlaySpeed('myAudio-002', 0.8)" type="button">0.8</button>
Note: replaced the audio files with something accessible so you can test this example live.
As required by license: music by audionautix.com

Stop audio on click and replay

<button class="button" style="width: 200px;" onclick="playSound()">Play sound</button>
function playSound() {
audio.pause();
var audio = new Audio('V2018-Museum-filer/mp3file.mp3');
audio.play();
}
When clicking the button multiple tiems to start the audio multiple times, i want to stop the audio already playing for it to replay. How can i do this? I get an error saying audio is undefined.
Hope this helps...
When the button is clicked, the audio is paused and restarts on second click.
function playSound() {
var audioControl = document.getElementById('sound');
var btn = $("#player");
if (btn.click && audioControl.paused !== true) {
audioControl.pause();
} else if (btn.click && audioControl.paused === true) {
audioControl.currentTime = 0;
audioControl.play();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="sound" controls>
<source src="http://www.largesound.com/ashborytour/sound/brobob.mp3" type="audio/mpeg">
</audio>
<button id="player" style="width: 200px;" onclick="playSound()">Play sound</button>

I need help getting autoplay to work via [getElementById]

My code: https://jsfiddle.net/m656xw8s/24/
I've been trying to get autoplay to work, can someone show me what the correct code would be? Using the code I provided. Using [getElementById]
var player = document.getElementById('player').autoplay; document.getElementById('player').innerHTML = true;
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;" onclick="
var player = document.getElementById('player').autoplay;
document.getElementById('player').innerHTML = true;
var player = document.getElementById('player').volume='1.0';
var button = document.getElementById('playButton');
var player = document.getElementById('player');
if (player.paused) {
playButton.style.backgroundColor = 'red';
player.play();
} else {
playButton.style.backgroundColor = 'red';
player.pause();
}">
</button>
<audio id="player" style="display:none;">
<source src='http://hi5.1980s.fm/;' type='audio/mpeg' />
</audio>
Set the autoplay then load.
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_prop_autoplay
Update:
document.getElementById('playButton').addEventListener('click', autoPlayToggle);
document.getElementById('autovolume_range').addEventListener('change', changeVol);
//Only getElementById once!
var player = document.getElementById("player");
var autoplaytext = document.getElementById("autoplay_text");
var autovolumetext = document.getElementById("autovolume_range");
//Boolean from localstorage to keep state of the player
var autoPlayOn = autoplaytext.value = (localStorage.getItem("keepAutoPlay") === "true");
var setVolumeOn = autovolumetext.value = parseFloat(localStorage.getItem("keepVolume"));
player.volume = setVolumeOn;
player.autoplay = autoPlayOn;
player.load();
//Force play if it dosen't autoplay after refresh
if (player.autoplay == true) {
player.play();
} else {
player.pause();
}
//Function
//When the user refreshes the page it will keep the autoplay state
function autoPlayToggle() {
if (player.paused) {
player.play();
player.autoplay = true;
} else {
player.pause();
player.autoplay = false;
}
//Show the state in a text box
autoplaytext.value = player.autoplay;
//Save updated state to your local disk
localStorage.setItem("keepAutoPlay", autoplaytext.value);
}
//Save state of volume
function changeVol() {
player.volume = this.value;
localStorage.setItem("keepVolume", this.value);
}
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;">
</button>
<audio id="player" style="display:none;" >
<source src='http://hi5.1980s.fm/;' type='audio/mpeg'/>
</audio>
AutoPlay: <input id="autoplay_text" />
AutoVolume: <input type="range" step="0.1" min="0.0" max="1.0" id="autovolume_range" />
https://jsfiddle.net/LeroyRon/dtnrdjd5/
You only need to add attribute auto play to your audio tag see the updated code below; Based on your code you are redeclaring player multiple times see the updated code below. Your auto play is triggered on button click based on your code, you may want to separate the javascript codes to the button and just trigger a method indicated on your button click event.
You will need to use removeAttribute to remove the autoplay from your audio element. I added the code on how to do it below.
//player declared outside of the audioPlay method to make it accessible inside the audioPlay method
var player = document.getElementById('player');
//auto play set outside playAudio method outside of the button click event method
player.setAttribute('autoplay', '');
//to set autoplay false uncomment the code below
//player.removeAttribute('autoplay');
//playAudio is triggered on button click event
function playAudio(){
player.setAttribute('volume', 1.0);
var button = document.getElementById('playButton');
if (player.paused) {
playButton.style.backgroundColor = 'red';
player.play();
} else {
playButton.style.backgroundColor = 'red';
player.pause();
}
}
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;" onclick="
playAudio()">
</button>
<audio id="player" style="display:none;">
<source src='http://hi5.1980s.fm/;' type='audio/mpeg' />
</audio>

How can I change play/button images in HTML5 audio?

I have the code of audio player. How can I change the picture of play/pause button when press?
<div class="onlineradio"><img src="images/Radio.jpg" alt="" />
<p><video id="yourAudio" width="0" height="0">
<source src='http://178.219.160.126:8000/stream.mp3' type='audio/mpeg' preload="auto" />
</video> <a id="audioControl" href="#"><img src="images/radioscalebutton.png" alt="" /></a></p>
</div>
<script>// <![CDATA[
var yourAudio = document.getElementById('yourAudio'),
ctrl = document.getElementById('audioControl');
ctrl.onclick = function () {
// Update the Button
var pause = ctrl.innerHTML === 'pause!';
ctrl.innerHTML = pause ? 'pause' : 'play';
// Update the Audio
var method = pause ? 'pause' : 'play';
yourAudio[method]();
// Prevent Default Action
return false;
};
// ]]></script>
I have implemented a final working solution with custom audio controls (play and pause) with toggling state button. If something is not clear for you, please ask.
Here is the working solution and the JSFiddle:
var yourAudio = document.getElementById('yourAudio'),
ctrl = document.getElementById('audioControl'),
playButton = document.getElementById('play'),
pauseButton = document.getElementById('pause');
function toggleButton() {
if (playButton.style.display === 'none') {
playButton.style.display = 'block';
pauseButton.style.display = 'none';
} else {
playButton.style.display = 'none';
pauseButton.style.display = 'block';
}
}
ctrl.onclick = function () {
if (yourAudio.paused) {
yourAudio.play();
} else {
yourAudio.pause();
}
toggleButton();
// Prevent Default Action
return false;
};
#audioControl img {
width: 50px;
height: 50px;
}
#pause {
display: none;
}
<div class="onlineradio">
<img src="images/Radio.jpg" alt="" />
<p>
<audio id="yourAudio">
<source src='http://178.219.160.126:8000/stream.mp3' type='audio/mpeg' preload="auto" />
</audio>
<a id="audioControl" href="#">
<img src="http://etc-mysitemyway.s3.amazonaws.com/icons/legacy-previews/icons/glossy-black-3d-buttons-icons-media/002110-glossy-black-3d-button-icon-media-a-media22-arrow-forward1.png" id="play"/>
<img src="https://www.wisc-online.com/asset-repository/getfile?id=415&getType=view" id="pause"/>
</a>
</p>
</div>
You can download the images of controls and use refer to them locally.

Javascript & HTML5 - button to play next video not working

Thanks for stopping by. I'm creating a page to cycle through video clips. The cycling through part (run() function) works just fine. I also created a few buttons to play the specific video clip and these are not working. I've only written the function for the first button and I'll write the other two when I get the first working.
Any help if greatly appreciated.
Thanks,
Tommy
<video id="tutorials" autoplay onended="run()"
autobuffer="true" width="600px" height="350px" controls>
<source src="video1.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
</video>
<br>
<br>
<button id="tut1">Play Tutorial 1</button>
<button id="tut2">Play Tutorial 2</button>
<button id="tut3">Play Tutorial 3</button>
<script type="text/javascript">
video_count =1;
videoPlayer = document.getElementById("tutorials");
function run()
{
video_count++;
if (video_count == 4) return;
var nextVideo = "video"+video_count+".mp4";
videoPlayer.src = nextVideo;
videoPlayer.play();
};
document.getElementByID("tut1").onclick = function()
{
videoPlayer.stop();
videocount = 1;
var video = "video1.mp4";
videoPlayer.src = video;
videoPlayer.play();
}
</script>
I'd prefer to structure the code this way:
<script type="text/javascript">
video_count =1;
videoPlayer = document.getElementById("tutorials");
function runNext()
{
runVideo(video_count+1);
}
function runVideo(number)
{
if (number > 3) return;
video_count = number;
videoPlayer.src = "video"+video_count+".mp4";
videoPlayer.play();
}
</script>
HTML:
<button id="tut1" onclick="runVideo(1);">Play Tutorial 1</button>
<button id="tut2" onclick="runVideo(2);">Play Tutorial 2</button>
<button id="tut3" onclick="runVideo(3);">Play Tutorial 3</button>

Categories