Cycle through audio using js - javascript

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

Related

How to use vid.onended to detect when a video is done playing using javascript

I am trying to create an HTML video playlist and currently I am using vid.onended to detect when a video is done playing (based of the current video src) and then play the next video when the video ends. This works perfectly for the first video but for some reason it never plays the second video and jumps straight to the third video.
My code:
//add video playlist functionality to auto play next video based on id
var vid = document.getElementById("urlVideo");
vid.onended = function() {
var video0 = "http://techslides.com/demos/sample-videos/small.mp4";
var video1 = "https://media.w3.org/2010/05/sintel/trailer.mp4";
var video2 = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
if (vid.src = video0) {
vid.src = video1;
}
if (vid.src = video1) {
vid.src = video2;
}
};
<video id="urlVideo" width="100%" height="460" controls autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
What am I doing wrong?
Edit:
Answer by Alen Toma works perfectly.
I Also managed to do it according to the current video source based on a comment by Quentin, For anyone else looking for how to do it explicitly with the current video source as the variable/condition, please see
https://jsfiddle.net/redlaw/qjb5h7e9/9/
I did make a small example below, it should help.
Have a look at this JSFiddle.
//add video playlist functionality to auto play next video based on id
var videoSrc = [
"https://media.w3.org/2010/05/sintel/trailer.mp4",
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
]
var vid = document.getElementById("urlVideo");
var index = 0;
vid.addEventListener("ended", function() {
var currentSrc = videoSrc[index];
index += 1;
if (index >= videoSrc.length)
index = 0; // Make Loop and jump to the first video
vid.src = currentSrc;
vid.play();
console.log(currentSrc)
}, true);
<video id="urlVideo" controls autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
you must use an event listener for your video player like this code:
var vid = document.getElementById("urlVideo");
vid.addEventListener("ended", function() { /* your code*/ }, true);

Javascript onended is detecting the end of the video

Everything in my code works. It just doesn't switch to the next song/video after finishing the current one. I have tried adding an onended event handler (in the tag and in JavaScript) but failed. I also tried jQuery but it did't work. For some reasons it doesn't change songs at the end of the song. Instead, it will replay the same song over and over again.
<video id="vid" src="main/" playsinline autoplay loop>
<script>
var video = document.currentScript.parentElement;
video.volume = 0.1;
var lastSong = null;
var selection = null;
var playlist = ["main/songn.mp4", "main/songl.mp4", "/main/songt.mp4", "/main/songf.mp4"]; // List of Songs
var video = document.getElementById("vid");
video.autoplay=true;
video.addEventListener("ended", selectRandom);
function selectRandom(){
while(selection == lastSong){
selection = Math.floor(Math.random() * playlist.length);
}
lastSong = selection;
video.src = playlist[selection];
}
selectRandom();
video.play();
</script>
</video>
You just need to remove the loop parameter from the video tag if you want to trigger the end event (doc):
<video id="vid" src="main/" playsinline autoplay>
(Your code will handle the loop by loading a new song when one ended.)
BTW, keep var video = document.getElementById("vid"); to refer to your <video> tag, it's shorter and cleaner than the first declaration.

Sequential playback of audio files overlap using .addEventListener ended

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.

Play multiple audio files sequentially or randomly in background using HTML5 and javascript

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');
});
}
});

use webkit-playsinline in javascript

How do I use webkit-playsinline in javascript instead of in html5 video tag? I want to use it just like using video tag control/autoplay attribute in javascript or if you guys have any other method that is working? I'm working on a PhoneGap iOS app that stream video.
Below is some approach that I have tried but none are working:
videoPlayer.WebKitPlaysInline = "webkit-playsinline";
videoPlayer.WebKitPlaysInline = "WebKitPlaysInline";
videoPlayer.webkit-playsinline = "webkit-playsinline";
videoPlayer.WebKitPlaysInline = "true";
videoPlayer.WebKitPlaysInline = true;
videoPlayer.webkit-playsinline = "true";
videoPlayer.webkit-playsinline = true;
My current code(js):
function loadPlayer() {
var videoPlayer = document.createElement('video');
videoPlayer.controls = "controls";
videoPlayer.autoplay = "autoplay";
videoPlayer.WebKitPlaysInline = true;
document.getElementById("vidPlayer").appendChild(videoPlayer);
nextChannel();
}
My current code(html):
<body onload="loadPlayer(document.getElementById('vidPlayer'));"><!-- load js function -->
<li><span class="ind_player"><div id="vidPlayer"></div></span></li><!-- video element creat here -->
Any helps are much appreciate. Thanks.
You can do this without jQuery:
var videoElement = document.createElement( 'video' );
videoElement.setAttribute('webkit-playsinline', 'webkit-playsinline');
You have to activate this functionality in your iOs application's WebView :
webview.allowsInlineMediaPlayback = true;
You can check this post for more details:
HTML5 inline video on iPhone vs iPad/Browser
You need to attach it to the video element and set it as video's attribute
such as :
<video class="" poster="" webkit-playsinline>
<source src="" type="video/ogg" preload="auto">
<source src="" type="video/mp4" preload="auto">
</video>
so you could do (with jQuery) :
$('video').attr('webkit-playsinline', '');

Categories