JavaScript - audio src - replace URL with variable - javascript

I've looked up similar questions, but haven't been able to make this work. Sorry if this is a basic question.
This works for me with an on-click button:
var player = document.createElement('audio');
player.src = 'http://jplayer.org/audio/ogg/Miaow-07-Bubble.ogg';
player.load();
player.play();
How can I replace the URL with a variable - "sound1", where the variable fetches a different URL? I tried this for the 2nd line, to no avail:
player.src = "'" + sound1 +"'";
Thanks.

You don't need " or '. Just use
player.src = sound1;
Assuming that sound1 just holds an URL.
For example:
var sound1 = 'http://jplayer.org/audio/ogg/Miaow-07-Bubble.ogg';
var player = document.createElement('audio');
player.src = sound1;
player.load();
player.play();

Related

why does this keep playing same video instead of random new video?

I'm making a random order video player, adapting code from here but the same video just keeps playing, even though I can see (from text above the video) that the random ordering is working. Live version is here.
Is the problem with the appendChild meaning the new video is end of a list but the first in list keeps playing? I tried replaceChild but that didn't work.
<script type="text/javascript">
$(document).ready(function(){
var videos = [
[{type:'mp4', 'src':'carlos/one-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/two-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/three-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/four-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/five-carlostest.mp4'}]
];
// selecting random item from array as first to be played
var randomitem = videos[Math.floor(Math.random()*videos.length)];
// This function adds a new video source (dynamic) in the video html tag
function videoadd(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
// this function fires the video for particular video tag
function newvideo(src){
var vid = document.getElementById("myVideo");
videoadd(vid,src ,'video/ogg');
vid.autoplay = true;
vid.load();
vid.play();
}
// function call
newvideo(randomitem[0].src)
// Added an event listener so that everytime the video finishes ,a new video is loaded from array
document.getElementById('myVideo').addEventListener('ended',handler,false);
function handler(){
var newRandom = videos[Math.floor(Math.random()*videos.length)];
newvideo(newRandom[0].src)
document.getElementById("monitor").innerHTML = "randomitem is " + newRandom[0].src;
}
})
</script>
Also, if anyone can tell me why the autoplay never works that'd be appreciated, though it's the least of my problems.
I have kinda found this solution for your video playing one after other. now in your JS file, now you just will need to add your video src path.
var vidElement = document.getElementById('video');
var vidSources = [
"https://lutins.co.uk/carlos/one-carlostest.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
var activeVideo = Math.floor((Math.random() * vidSources.length));
vidElement.src = vidSources[activeVideo];
vidElement.addEventListener('ended', function(e) {
// update the active video index
activeVideo = (++activeVideo) % vidSources.length;
if(activeVideo === vidSources.length){
activeVideo = 0;
}
// update the video source and play
vidElement.src = vidSources[activeVideo];
vidElement.play();
});
video {
width:350px;
}
<p>wowww you got it!</p>
<video src="https://lutins.co.uk/carlos/one-carlostest.mp4" id="video" autoplay muted playsinline></video>
Change the randomIt variable into a callback, only this way, it will generate new random number each time it get call.
// I have change randomitem into a function with ofcourse a proper name
var getRandomItem = function() {
return videos[Math.floor(Math.random()*videos.length)];
}
You should also call it properly like this:
//newvideo(randomitem[0].src) -> change it to
newvideo(getrandomItem().src)
There might also other adjustments requires for your code to work.

javascript + html5 audio player cors not play dynamic source

Sorry for my English, I'm using a translator.
The question is the following: passing the source of an audio file hosted on Google Drive doesn't work.
But if I pass a source of a local file it works.
Also if the mp3 files are in my domain, it works as well.
Example:
function _playDrive() { //dont work
let audio = new Audio('http://docs.google.com/uc?export=download&id=ejemplo'); //is mp3
audio.controls = true;
audio.crossOrigin = 'anonymous';
document.body.appendChild(audio);
audio.play();
}
function _playLocal() { //work
let audio = new Audio('./mysong.mp3');
audio.controls = true;
audio.crossOrigin = 'anonymous';
document.body.appendChild(audio);
audio.play();
}
I would appreciate a solution with no dependencies, thx.
You need to get the file id which is a 20+ alphanumeric located after id= in the url.
Base
https://drive.google.com/uc?export=download&confirm=no_antivirus&id=
File_ID
0B1c82XNzuQ5ZU3RYSmZENERBQjQ
SOLUTION
var player = new Audio(Base + File_ID )
Demo
var player = new Audio('https://drive.google.com/uc?export=download&confirm=no_antivirus&id=0B1c82XNzuQ5ZU3RYSmZENERBQjQ');
player.controls = true;
document.body.appendChild(player);
player.play();

How to play video dynamically when its source is changed

I have got a
<input type="file" id="howtovideo" name="howtovideo" accept="video/mp4"> </span>
When its changed , i am calling the below function to play video dynamically
$("#howtovideo").on('change', function() {
loadVideo();
});
function loadVideo(){
alert('loadVideo called');
var newsrc = 'http://clips.vorwaerts-gmbh.de/VfE_html5.mp4';
var video = document.getElementById('video');
var source = document.createElement('source');
source.setAttribute('src', newsrc);
video.appendChild(source);
video.play();
}
But nothing is happening and there are no errors in console demo.
Could you please let me know how to play vdeo dynamicaly ??
You don't need to add new source tag. Only set address of new video to src attribute of current source tag. Note that after changing src, you need to load video using .load() and then play video. Also if you have jQuery, use it to finding elements.
$("#howtovideo").on('change', function(){
loadVideo();
});
function loadVideo(){
var newsrc = 'http://clips.vorwaerts-gmbh.de/VfE_html5.mp4';
$('#video > source').attr('src', newsrc);
$("#video")[0].load();
$("#video")[0].play();
}

audio auto play next song when previous is finished

I want to create an audio background player where user can only click on image to play or stop the playback. I have trouble creating or rewirting existing codes to make a playlist for it, that automatically plays next song when previous is finished. I want to do it in vanilla js.
Here is what I have so far:
https://jsfiddle.net/rockarou/ad8Lkkrj/
var imageTracker = 'playImage';
swapImage = function() {
var image = document.getElementById('swapImage');
if (imageTracker == 'playImage') {
image.src = 'http://findicons.com/files/icons/129/soft_scraps/256/button_pause_01.png';
imageTracker = 'stopImage';
} else {
image.src = 'http://findicons.com/files/icons/129/soft_scraps/256/button_play_01.png';
imageTracker = 'playImage';
}
};
var musicTracker = 'noMusic';
audioStatus = function() {
var music = document.getElementById('natureSounds');
if (musicTracker == 'noMusic') {
music.play();
musicTracker = 'playMusic';
} else {
music.pause();
musicTracker = 'noMusic';
}
};
here is the trick to trigger next song:
music.addEventListener('ended',function(){
//play next song
});
How to play another song on same audio tag:
music.pause();
music.src = "new url";
music.load();
music.play();
Now here is a cool example of a playlist in html5, you can load each song at the time, case some clients (mobile) will not be happy when you consume the traffic, in next example all audios are loaded at same time to have a smooth transition from song to song,
loading the songs:
//playing flag
var musicTracker = 'noMusic';
//playlist audios
var audios = [];
$(".song").each(function(){
var load = new Audio($(this).attr("url"));
load.load();
load.addEventListener('ended',function(){
forward();
});
audios.push(load);
});
//active track
var activeTrack = 0;
Highlighting witch song is playing, with a bit of jquery, yeah, case yeah I'm lazy, lazy:
var showPlaying = function()
{
var src = audios[activeTrack].src;
$(".song").removeClass("playing");
$("div[url='" + src + "']").addClass("playing");
};
Fiddle here
Note: If the sound's doesn't play, manually check if audio url's are accessible
[Here a non vanilla solution.] My playlist consists of four songs, they are named 0.mp3, 1.mp3, 2.mp3 and 3.mp3.
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head>
<body>
<audio id="player" autoplay controls><source src="0.mp3" type="audio/mp3"></audio>
</body>
<script>
var x = 0;
var music = document.getElementById("player");
$("#player").bind("ended", function(){
x=x+1;
music.src = x%4 + ".mp3";
music.load();
music.play();
});
</script>
</html>
The playlist is repeated indefinetely.
Vanilla Javascript variant:
const audioArray = document.getElementsByClassName('songs'); //Get a list of all songs
let i = 0; //Initiate current Index
const player = document.getElementById('player'); //get the player
player.src = audioArray[i].getAttribute('data-url'); //set first Song to play
player.addEventListener('ended',function(){ //when a song finished playing
i++; //increase index
if (i < audioArray.length) { //If current index is smaller than count of songs
player.src = audioArray[i].getAttribute('data-url'); //set next song
return; // stop further processing of this function for now
}
// current index is greater than count of songs
i = 0; // therefore we reset the current index to the first available song
player.src = audioArray[i].getAttribute('data-url'); // and set it to be played
});
In this example you don't set an initial src for the audioplayers source-tag but instead have a list of class 'song'-items with an data-url attribute containing the url/path to the tracks.
I added comments to learn what and why this code is doing what it does.
Of course it could be better but it's a quick throwup of code ;)

Javascript/HTML5: get current time of audio tag

I have an audio tag in my template and I need to show currentTime of it on a button click. Please check my code below:
var myaudio = document.getElementsByTagName("audio")[0];
var cur_time = myaudio.currentTime;
$('#curPosition').val(cur_time);
But it always returns 0 as current time while the audio is playing. Do anybody have any idea on this ?
Thanks
It is a typo. You declare var myaudio and then you use audio.currentTime not myaudio.currentTime
Try:
var myaudio = document.getElementsByTagName("audio")[0];
var cur_time = myaudio.currentTime;//<-----Change here
$('#curPosition').val(cur_time);
DEMO
you can try like this
<audio id="track" src="http://upload.wikimedia.org/wikipedia/commons/a/a9/Tromboon-sample.ogg"
ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration);">
<p>Your browser does not support the audio element</p>
</audio>
<span id="tracktime">0 / 0</span>
<button onclick="document.getElementById('track').play();">Play</button>
or in javascript you can do this
<audio id='audioTrack' ontimeupdate='updateTrackTime(this);'>
Audio tag not supported in this browser</audio>
<script>
function updateTrackTime(track){
var currTimeDiv = document.getElementById('currentTime');
var durationDiv = document.getElementById('duration');
var currTime = Math.floor(track.currentTime).toString();
var duration = Math.floor(track.duration).toString();
currTimeDiv.innerHTML = formatSecondsAsTime(currTime);
if (isNaN(duration)){
durationDiv.innerHTML = '00:00';
}
else{
durationDiv.innerHTML = formatSecondsAsTime(duration);
}
}
</script>
I am currently getting time out of javascript

Categories