The goal is to make many buttons with different audio playing when clicked. Every time user is clicking on one button, it is toggling audio. If non-playing button for different audio is pressed, first audio stops and only after that 2nd one plays.
At this moment there are 2 buttons, everything almost working fine, except when 'B' audio has class 'playing' and you click on 1st audio button class won't remove from the 2nd one and they start to play simultaneously.
How is possible to make stop audio instead of pause when clicked on any of the button?
<script>
function play(chord) {
var audio = document.getElementById(chord);
var active = document.querySelector('.playing');
var everyAudio = document.querySelector('audio');
if(audio.classList.contains('playing')){
audio.pause();
}else {
everyAudio.pause();
everyAudio.classList.remove('playing');
audio.play();
}
audio.classList.toggle('playing');
}
</script>
<input type="button" value="C Major" onclick="play('C')">
<audio id="C">
<source src="Tveice_A_09.09.wav" type="audio/wav">
</audio>
<input type="button" value="B Major" onclick="play('B')">
<audio id="B">
<source src="Black_sand_cello1_raw.wav" type="audio/wav">
</audio>
Thank you for the answer on the first question. With your advice, toggling started to work:
var everyAudio = document.querySelectorAll('audio');
if(audio.classList.contains('playing')){
audio.pause();
}else{
for (var i = 0; i < everyAudio.length; i++){
everyAudio[i].classList.remove('playing');
everyAudio[i].pause();
}
audio.play();
}
Instead of using document.querySelector use document.querySelectorAll - the latter will return an array of elements, the prior will only return 1 element.
More info on document.querySelectorAll
The following may be the cause.
var everyAudio = document.querySelector('audio');
querySelector returns only one element.
Please use querySelectorAll to get the array.
Call pause for each of them.
First question was answered thanks to your advices to use document.querySelectorAll instead of document.querySelector, and then check whole array. Thank you!
For second question I've found solution by myself. Simply need to use audio currentTime audio parameter. So it looks like this in the end.
<script>
function play(chord) {
var audio = document.getElementById(chord);
var active = document.querySelector('.playing');
var everyAudio = document.querySelectorAll('audio');
if(audio.classList.contains('playing')){
audio.pause();
}else{
for (var i = 0; i < everyAudio.length; i++){
everyAudio[i].classList.remove('playing');
everyAudio[i].pause();
everyAudio[i].currentTime = 0;
}
audio.play();
}
audio.classList.toggle('playing');
}
</script>
<input type="button" value="C Major" onclick="play('C')">
<audio id="C">
<source src="Tveice_A_09.09.wav" type="audio/wav">
</audio>
<input type="button" value="B Major" onclick="play('B')">
<audio id="B">
<source src="Black_sand_cello1_raw.wav" type="audio/wav">
</audio>
Related
When the play button is clicked I want the mp3/ogg file to start playing from different randomised points.
There's only one button and no visible player for the user to toggle round. It's meant to be like a radio effect.
I am quite new to javascript so need a bit of help. I think I need to have a bit of code that tells it to skip 10-30s randomly through the file. But not sure how to go about it.
Code here:
<a onclick="javascript:toggleSound();"><li><i class="fa fa-play-circle" aria-hidden="true"></i></li></a>
<audio id="audio" preload="auto">
<source src="audio/filename.mp3" type="audio/mpeg"/>
<source src="audio/filename.ogg" type="audio/ogg"/>
function toggleSound() {
var audioElem = document.getElementById('audio');
if (audioElem.paused)
audioElem.play();
else
audioElem.pause();
Try this:
function toggleSound() {
var audioElem = document.getElementById('audio');
if (audioElem.paused) {
audioElem.currentTime = parseInt(Math.random() * 20) + 10;
audioElem.play();
}
else
audioElem.pause();
}
I'm trying to use a button to change the audio track to 1 of 2 being played in the browser, however, the method I found switches to the second track but doesn't change the audio played afterwards, it only restarts the second track. Here's my code:
function loadSong(){
var player=document.getElementById('player');
var source1=document.getElementById('player');
var source2=document.getElementById('player');
source1.src='/audio/mac+.mp3';
source2.src='/audio/mac-slowed.mp3';
player.load(); //just start buffering (preload)
player.play(); //start playing
}
HTML
<audio id="player" autoplay="autoplay" preload="auto" loop="loop">
<source id="source1" src="/audio/mac+.mp3" type="audio/mpeg">
<source id="source2" src="" type="audio/mpeg">
</audio>
<button onclick='loadSong()'>Switch the Music!</button>
Based on the information you provided in your original inquiry, this is most likely the best fit for you. Attached is a working JSFiddle for you review. You will need to update the src files with your own locally stored files.
HTML:
<audio id="source1" autoplay="autoplay" loop="loop" src='http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3'></audio>
<audio id="source2" loop="loop" src='http://www.stephaniequinn.com/Music/Pachelbel%20-%20Canon%20in%20D%20Major.mp3'></audio>
<button id="player">Switch the music to track # 2</button>
Javascript:
var player = document.getElementById('player');
var source1 = document.getElementById('source1');
var source2 = document.getElementById('source2');
player.onclick = function() {
curTrack = this.innerHTML.replace(/Switch the music to track # /, "");
if (curTrack == "1") {
nextTrack = "2";
source1.play();
source2.pause();
source2.currentTime = 0;
} else {
nextTrack = "1";
source2.play();
source1.pause();
source1.currentTime = 0;
}
this.innerHTML = "Switch the music to track # " + nextTrack;
}
You are overwriting the #player element look at your code you are saving the same selector to source1 and source 2 so change the selector of source one to source1 and source2
The following code is intended to play a series of short audio files in a sequence, as held in a javascript array named audio_sequence.
an .addEventListener('ended',function()) is used to trigger playback of each audio clip in the sequence.
This works as expected for the first 5 items in the array, playing each in turn, but then the audio elements start to play simultaneously and the sequence becomes jumbled.
I have tried several different approaches all yielding similar results.
Would very much appreciate any insights.
And example of the code running can be found here:
Play Sequence
Here's the javascript:
<script type="text/javascript">
var game_sounds = ["rooms", "bars", "food", "inveraray", "arse"];
var game_sequence = [0,1,2,3,4,0,1,2,3,4,0,1,2,3,4];
var sequence_position = 0;
function play_next(){
if (sequence_position < game_sequence.length){
var audioElement = document.getElementById(game_sounds[game_sequence[sequence_position]]);
audioElement.addEventListener('ended', function(){
sequence_position++;
play_next();
}, true);
audioElement.play();
}
}
function playSequence(){
sequence_position = 0;
var audioElement = document.getElementById(game_sounds[game_sequence[sequence_position]]);
// alert(game_sounds[game_sequence[sequence_position]]);
audioElement.addEventListener('ended', function(){
sequence_position++;
play_next();
},true);
audioElement.play();
}
</script>
& the html is as follows:
<a onClick="javascript:playSequence();" href="#"><h2>Play Sequence</h2></a>
<audio hidden id="rooms" preload="auto">
<source src="/audio/rooms.mp3">
</audio>
<audio hidden id="food" preload="auto">
<source src="/audio/food.mp3" >
</audio>
<audio hidden id="bars" preload="auto">
<source src="/audio/bars.mp3">
</audio>
<audio hidden id="inveraray" preload="auto">
<source src="/audio/inveraray.mp3">
</audio>
<audio hidden id="arse" preload="auto">
<source src="/audio/arse.mp3">
</audio>
What is causing the problem is that you are attaching the same event listener several times to each element, as they are in a loop. In a non particularly elegant but effective workaround, you could remove the listener before attaching it again:
var game_sounds = ["rooms", "bars", "food", "inveraray", "arse"];
var game_sequence = [0,1,2,3,4,0,1,2,3,4,0,1,2,3,4];
var sequence_position = 0;
function play_next(){
if (sequence_position < game_sequence.length){
playSequence();
}
}
function playSequence(){
var audioElement = document.getElementById(game_sounds[game_sequence[sequence_position]]);
// alert(game_sounds[game_sequence[sequence_position]]);
audioElement.removeEventListener('ended', prepareNextAudio);
audioElement.addEventListener('ended', prepareNextAudio, true);
audioElement.play();
}
function prepareNextAudio() {
sequence_position++;
play_next();
}
This code works and stops the playlist when each audio has been played for three times, which I guess is what you needed.
I am trying to play 3 audio files (with the possibility of more later) that run in the background. At this point I am simply trying to play them sequentially and have it loop back to the first audio file when the last is played. I believe I have tried almost every solution or combination of functions and I just can't get it to work. I run into one of two problems:
If I try using repetition with each audio stored in the array, the page will successfully play the first then tries to play the next two simultaneously, rather than sequentially. And it certainly does not go back to the first. Furthermore, if you notice in my html, I have a seperate ID for each player. Would it be better to put them all in the sample player ID?
jQuery(document).ready(function (){
var audioArray = document.getElementsByClassName('playsong');
var i = 0;
var nowPlaying = audioArray[i];
nowPlaying.load();
nowPlaying.play();
while(true){
$('#player').on('ended', function(){
if(i>=2){
i=0;
}
else{
i++;
}
nowPlaying = audioArray[i];
nowPlaying.load();
nowPlaying.play();
});
}
});
On the other hand, I can play each sequentially but each play needs to be hardcoded for and I cannot loop back to the first
jQuery(document).ready(function (){
var audioArray = document.getElementsByClassName('playsong');
var i = 0;
var nowPlaying = audioArray[i];
nowPlaying.load();
nowPlaying.play();
$('#player').on('ended', function(){
// done playing
//alert("Player stopped");
nowPlaying = audioArray[1];
nowPlaying.load();
nowPlaying.play();
$('#player2').on('ended', function(){
nowPlaying = audioArray[2];
nowPlaying.load();
nowPlaying.play();
});
});
});
Here is my html
<audio id="player" class = "playsong">
<source src="1.mp3" />
</audio>
<audio id="player2" class = "playsong">
<source src="2.mp3" />
</audio>
<audio id="player3" class = "playsong">
<source src="3.mp3" />
</audio>
I am not terribly familiar with javascript, I am wondering if there is another event trigger function built into JS that I am not using? Some help is greatly appreciated.
HTML
<audio id="song-1" preload class="songs">
<source src="1.mp3" type="audio/mpeg" />
</audio>
<audio id="song-2" preload class="songs">
<source src="2.mp3" type="audio/mpeg" />
</audio>
<audio id="song-3" preload class="songs">
<source src="3.mp3" type="audio/mpeg" />
</audio>
<audio id="song-4" preload class="songs">
<source src="4.mp3" type="audio/mpeg" />
</audio>
JS
jQuery(document).ready(function (){
var audioArray = document.getElementsByClassName('songs');
var i = 0;
audioArray[i].play();
for (i = 0; i < audioArray.length - 1; ++i) {
audioArray[i].addEventListener('ended', function(e){
var currentSong = e.target;
var next = $(currentSong).nextAll('audio');
if (next.length) $(next[0]).trigger('play');
});
}
});
I'm having trouble getting HTML5 audio to loop on my website: http://oclock.webs.com.
(It's an alarm which, when the alarm goes off, is supposed to loop a 1 second alarm sound over and over until you click OK on the alert box).
Simply including "loop" in the audio tag wasn't doing anything.
I found a helpful post on StackOverflow which lead me to this website: http://forestmist.org/2010/04/html5-audio-loops/
I knew Method 1 and 2 wouldn't work for me since they don't work on Firefox and are iffy on Chrome, and so Method 3 should have worked, unfortunately it didn't. Method 3 works when I'm on that website's page, but not when the code is included in my own page so I think there may be some conflicting code.
Relevant part of my webpage:
<audio id="audio1" preload>
<source src="media/alarm.ogg" type="audio/ogg" />
<source src="media/alarm.mp3" type="audio/mpeg" />
</audio>
<audio id="audio2" preload>
<source src="media/alarm.ogg" type="audio/ogg" />
<source src="media/alarm.mp3" type="audio/mpeg" />
</audio>
Relevant Javascript of the page:
if(timer==true && hours==hv && mins==mv && secs==sv){
document.getElementById("audio1").play();
alert("o'clock: Alarm ringing!");
document.getElementById("alarm").value="Set Alarm";
document.getElementById('audio1').addEventListener('ended', function(){
this.currentTime = 0;
this.pause();
document.getElementById('audio2').play();
}, false);
document.getElementById('audio2').addEventListener('ended', function(){
this.currentTime = 0;
this.pause();
document.getElementById('audio1').play();
}, false);
}
else{
document.getElementById("audio1").pause();
document.getElementById("audio2").pause();
document.getElementById("audio1").currentTime = 0;
document.getElementById("audio2").currentTime = 0;
}
Intention: Upon the computer's time matching that of the selected time on the page, the audio alarm will repeat (loop) until the user clicks OK on the alert box popup.
Problem: Currently it only plays through the audio once, it doesn't loop. Where did I mess up?
"ended event" or "loop" property dose not work on some browsers.
So I used window.setInterval() for looping audio playing.
For this method, you should know play time of Audio file in advanced.
function playAudioWithLoop (/**HTMLAudioElement*/audio, /**Number*/length)
{
function onEnd (){
audio.play();
}
/* length is msec */
if(length > 0) {
audio.__timer = window.setInterval(onEnd, length);
}
}
function stopAudioWithLoop (/**HTMLAudioElement*/audio)
{
if(audio.__timer) {
audio.__timer = window.clearInterval(audio.__timer);
}
}
======================================================================
***playAudioWithLoop(document.getElementById("audio1"), 12*1000);***
***stopAudioWithLoop(document.getElementById("audio1"));***