Javascript Function to Autoplay Random HTML Audio After Delay - javascript

I am trying to write some javascript code with some jQuery that will play a random sound file (selected from an array) to play periodically by setting a random amount of time to delay between sounds. So far, I have gotten the random song selector to work. However, there seems to be an issue with the recursion in the playMusic function. Only two songs will play back-to-back then stop with no delay between the songs.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var randInterval = 0;
var songList = ["song1","song2","song3","song4","song5"];
var songHTML;
function getRandomSong(){
var randSong = songList[Math.floor(Math.random()*songList.length)];
songHTML = "<source src='music/" + randSong + ".mp3'>" +
"<source src='music/" + randSong + ".ogg'>";
return songHTML;
}
function setRandomInterval(){
randInterval = Math.floor((Math.random()*60)+60);
return randInterval;
}
function playMusic(){
var delayTime = setRandomInterval();
$(document).ready(function(){
$('#myAudio').html(getRandomSong());
$('#myAudio').prop("volume", 0.05);
$('#myAudio').get(0).play();
});
$('#myAudio').on('ended', function(){
$('#myAudio').delay(delayTime).queue(function(){
return playMusic();
});
});
}
</script>
</head>
<body onload="playMusic()">
<div>
<audio controls id="myAudio" autoplay>
</audio>
</div>
</body>
</html>

I figured out how to do this. Below is the code that works correctly. I removed any JQuery related code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var randInterval = 0;
var songList = ["song1","song2","song3","song4","song5"];
var myAudio = new Audio("music/" + songList[Math.floor(Math.random()*songList.length)] + ".mp3");
//Generates a random song, sets it attributes/properties, and
//appends a file extension that works with the browser.
function getRandomSong(){
var randSong = songList[Math.floor(Math.random()*songList.length)]
if (myAudio.canPlayType('audio/mp3;')) {
myAudio.src="music/" + randSong + ".mp3";
} else {
myAudio.src="music/" + randSong + ".ogg";
}
myAudio.id="myAudio";
myAudio.volume=0.15;
myAudio.load();
myAudio.controls=false
myAudio.preload=false;
}
//Sets a random interval for the setTimeout Function with the
//'variation' parameter being a random amount of time in
//seconds, and the 'range' parameter being a set amount of time
//in seconds.
function getRandomInterval(variation, range){
randInterval = Math.floor((Math.random()*1000*variation)+(1000*range));
return randInterval;
}
//Gets a random song and plays that song.
function playMusic(){
getRandomSong();
myAudio.play();
}
</script>
</head>
<body>
<script type="text/javascript">
//Plays music on page load.
playMusic();
//Event Listener that will start a new song after a pause
//of randomly determined length.
myAudio.addEventListener('ended', function(){setTimeout(function(){playMusic();}, getRandomInterval(2,2));}, false);
</script>
</body>
</html>

Related

Automatically load next image from array everytime user enters website

So this code selects random image whenever a person loads my website, how can I change the code so that images are selected sequentially from first to last everytime a person loads the website and then again resets to first image when the counter reaches the end?
P.s- The code works fine on hosting server, here it gives an error i don't know why.
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
You can use localstorage to achieve this. When the user enters the website, you can do something like:
var pictureIndex = localstorage.getItem("pictureIndex");
But since it may be the user's first visit, it would be better to have:
var pictureIndex = localstorage.getItem("pictureIndex") || 0;
Then, you just increment the pictureIndex and perform a modulo operation (for the case when this is the last image)
pictureIndex = (pictureIndex + 1) % myPix.length;
To save this index, you can use
localStorage.setItem('pictureIndex', pictureIndex);
Next time when the user refreshes the page (or comes back), he will get the next picture in your array.
The final code should look like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var pictureIndex = window.localStorage.getItem("pictureIndex") || 0;
pictureIndex = (pictureIndex + 1) % myPix.length;
window.localStorage.setItem("pictureIndex", pictureIndex);
document.getElementById("imgid").innerHTML = pictureIndex;
document.getElementById("myPicture").src = myPix[pictureIndex];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
Press "Run" multiple times to cycle through the images.
Currently showing: <span id="imgid"></span>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
Note that the above code might not work here (but you can test it locally) due to some security restrictions from jsfiddle. A working version can be accessed >here<
function choosePic() {
var local_item = 0;
if(localStorage.getItem('pic_key')){
local_item = parseInt(intvlocalStorage.getItem('pic_key'));
}
if(local_item >= myPix.length){
local_item = 0;
}
localStorage.setItem('pic_key', local_item + 1);
document.getElementById("myPicture").src = myPix[local_item];
}
You can use LocalStorage to achieve this. When the user enters the website, you can store the key and increment it.
Use local storage to save the data you need [e.g. visited = 3(3rd time the same person visited your website)]
Your js code can be implemented like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
if (localStorage.getItem('visited') == null)
{
document.getElementById("myPicture").src = myPix[0];
localStorage.setItem('visited', 1);
}
else if (localStorage.getItem('visited') >= myPix.length)
{
localStorage.setItem('visited', 0);
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
}
else
{
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
localStorage.setItem('visited', localStorage.getItem('visited') + 1);
}
}

html5 movie playlist, How to Count file

i have this code for autoplay (playlist) movie
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Movie Playlist</title>
<script>
var videoPlayer;
var video_count = 1;
window.onload = function (){
videoPlayer = document.getElementById("homevideo");
videoPlayer.addEventListener("ended", function (){
video_count++;
if (video_count == 6) video_count = 1;
var nextVideo = video_count+".mp4";
videoPlayer.src = nextVideo;
}, false);
}
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div style="width:100%;margin:0px auto;">
<video id="homevideo" width="100%" autoplay autobuffer src="1.mp4"></video>
</div>
on the code above, i have 5 .mp4 movie, but if i have more than 5 .mp4 movie, the 6.mp4, 7.mp4 and other will not be played. so, how can i dynamically set the movie count pure using html5 or javascript?
You are better off having your server provide this information.
But for your existing approach, I'm assuming your video names are in sequential order ... so 1.mp4, 2.mp4, 3.mp4, etc ... so you could keep looping through the videos while increasing the count, and once a video fails to load at a given video_count, you can know that it is the limit and loop back to the start if you wanted.
function videoExists(videoUrl){
var http = new XMLHttpRequest();
http.open('HEAD', videoUrl, false);
http.send();
return http.status != 404;
}
So, for example ...
var videoPlayer;
var video_count = 1;
var video_max = 0;
window.onload = function (){
videoPlayer = document.getElementById("homevideo");
videoPlayer.addEventListener("ended", function (){
var nextVideo = (video_count+1)+".mp4";
if(video_count <= video_max || videoExists(nextVideo)){
videoPlayer.src = nextVideo;
video_count++;
}else{
video_max = video_count;
//reset back to original video
video_count = 1;
videoPlayer.src = video_count+".mp4";
}
}, false);
}
I didn't test the code, but you should get the idea. Please let me know if you have any questions about this approach.

javascript code working in jsfiddle but not working in the browser [duplicate]

This question already has answers here:
JSFiddle code not working in my own page
(3 answers)
Closed 8 years ago.
my code is working in jsfiddle but not working in the browser i dont know what i missed here could you please check it and tell me the solution. i google it but i am not getting correct solution please help me
this is jsfiddle link http://jsfiddle.net/pLTrJ/9/
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
</head>
<script type="text/javascript">
var random = 0;
var theDiv = document.getElementById("showVal");
updateTheDiv(9,0);
function updateTheDiv(inRange, inMin) {
random = (Math.random()*inRange+inMin)|0;
theDiv.innerHTML = random;
var nextCall = (Math.random()*1000)|0;
setTimeout(function() {
updateTheDiv(inRange, inMin);
}, nextCall);
}
</script>
<body>
<div id="showVal"></div>
</body>
</html>
jsfiddle has wrapped it automatically in the onload event. You haven't done this in your HTML page, so when it runs in the browser you're trying to get hold of the div before it's been rendered, so theDiv is null.
The below should work:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
</head>
<script type="text/javascript">
window.onload = function () {
var random = 0;
var theDiv = document.getElementById("showVal");
updateTheDiv(9, 0);
function updateTheDiv(inRange, inMin) {
random = (Math.random() * inRange + inMin) | 0;
theDiv.innerHTML = random;
var nextCall = (Math.random() * 1000) | 0;
setTimeout(function () {
updateTheDiv(inRange, inMin);
}, nextCall);
}
}
</script>
<body>
<div id="showVal">
</div>
</body>
</html>
Try this in your Browser ;)
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
</head>
<body>
<div id="showVal"></div>
</body>
<script type="text/javascript">
var random = 0;
var theDiv = document.getElementById("showVal");
updateTheDiv(9,0);
function updateTheDiv(inRange, inMin) {
random = (Math.random()*inRange+inMin)|0;
theDiv.innerHTML = random;
var nextCall = (Math.random()*1000)|0;
setTimeout(function() {
updateTheDiv(inRange, inMin);
}, nextCall);
}
</script>
</html>
(I just put the script to the bottom. So the script loads after your element is set.)

Playing a loop of videos by javascript

I am trying to write code to play a continous loop of two videos. I have tried to do so by this code, but it has not been done. Being new to html5 and javascript need help to make required corrections.
<!doctype html>
<html><head>
<script>
var videoSource = new Array();
videoSource[0]="videfirst.mp4";
videoSource[1]="videosecond.mp4";
var videoCount = videoSource.length;
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
function videoPlay(videoNum)
{
document.getElementById("myVideo").setAttribute("src",videoSource [videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener ('ended',myHandler,false);
function myHandler() {
i++;
if(i == (videoCount-1)){
i = 0;
videoPlay(i);
}
else{
videoPlay(i);
}
}
</script>
</head>
<body>
<video controls height="180" width="300" id="video" >
</video>
</body>
</html>

Hide HTML5 audio player using javascript if dynamic audio src is not found or is null

First Post on Stackoverflow so bear with me please.
I have a JQMobile web app that is generating dynamic audio file links via JSON and appending the audio player per id. I am trying to hide the player when a src is not found.
The php/mysql/jqm scripting is working, I just cannot seem to get the if/else portion it always shows the player empty or not.
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<script type="text/javascript">
var serviceURL = "http://localhost/Apps/services/";
$(document).on('pageshow', '#detailsPage', function(event) {
var id = getUrlVars()["id"];
$.getJSON(serviceURL + 'getartist.php?id='+id, displayArtist);
});
function displayArtist(data) {
var artistDetVal = data.item;
console.log(artistDetVal);
$('#artistDetPic').attr('src', 'pics/lg/' + artistDetVal.picture);
$('#fullName').text(artistDetVal.firstName + ' ' + artistDetVal.lastName);
$('#artistDetTitle').text(artistDetVal.bio);
$('#city').text(artistDetVal.city);
$('#audioBio').attr('src', 'audio/' + artistDetVal.audio) .detach().appendTo($("#audioPlayer"));
}
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
<body>
<script type="text/javascript">
$(document).ready(function(){
function displayArtist(data) {
var artistDetVal = data.item;
$('#audioBio').text(artistDetVal.audio);
if (artistDetVal.audio>0) {
$("#audioPlayer").show();
}
else {
$("#audioPlayer").hide();
}
}
});
</script>
<audio id="audioPlayer" controls="controls"><source id="audioBio" src=""/></audio>
</body>
</html>
It seems as if your function displayArtist is being declared twice which is a "no-no". Also, the second declaration, which is the one which controls whether to show or hide the player, is never called.
Try putting the logic for showing/hiding the player in your first instance of displayArtist and removing the duplicate altogether.
function displayArtist(data) {
var artistDetVal = data.item;
console.log(artistDetVal);
$('#artistDetPic').attr('src', 'pics/lg/' + artistDetVal.picture);
$('#fullName').text(artistDetVal.firstName + ' ' + artistDetVal.lastName);
$('#artistDetTitle').text(artistDetVal.bio);
$('#city').text(artistDetVal.city);
$('#audioBio').attr('src', 'audio/' + artistDetVal.audio).detach().appendTo($("#audioPlayer"));
$('#audioBio').text(artistDetVal.audio);
if (artistDetVal.audio>0) {
$("#audioPlayer").show();
}
else {
$("#audioPlayer").hide();
}
}
Also, if artistDetVal.audio is a string you may want to use the condition if(artistDetVal.audio.length > 0)

Categories

Resources