How to play multiple random songs in HTML - javascript

So I'd like to have a button in the center of my page to initiate a playlist of randomly selected songs. Once the button is clicked, it should disappear and an audio control window spanning the entire width of the screen should pop up along the bottom of the screen. I've got five mp3 files I'm playing around with. I currently have a start, pause, and resume button, but they're freestanding ugly buttons. Here's a bit of code I have:
<audio id="blue">
<source src="blue.mp3" type="audio/mpeg">
</audio>
<audio id="cigar">
<source src="cigar.mp3" type="audio/mpeg">
</audio>
<audio id="immigrant">
<source src="immigrant.mp3" type="audio/mpeg">
</audio>
<audio id="monkey">
<source src="monkey.mp3" type="audio/mpeg">
</audio>
<audio id="money">
<source src="money.mp3" type="audio/mpeg">
</audio>
<script>
var a1 = document.getElementById("blue");
var a2 = document.getElementById("cigar");
var a3 = document.getElementById("immigrant");
var a4 = document.getElementById("monkey");
var a5 = document.getElementById("money");
var x;
function playAudio() {
var num = Math.floor(Math.random() * 5) + 1;
if(num == 1){
x = a1;
x.play();
}else if(num == 2){
x = a2;
x.play();
}else if(num == 3){
x = a3;
x.play();
}else if(num == 4){
x = a4;
x.play();
}else if(num == 5){
x = a5;
x.play();
}
}
function pauseAudio() {
x.pause();
}
function resumeAudio() {
x.play();
}
</script>
I'm just completely lost as to how I can incorporate all this into something like this:
<audio controls>
<source src="fileName.mp3" type="audio/mpeg">
</audio>
One of the major issues is that I don't know of a way to queue up a song (randomly) and have it play once the previous song ends. I did some Googling but I either couldn't understand what I saw, or it wasn't quite what I need.

How about something like this:
HTML:
<audio id="player" controls></audio>
JavaScript:
const audioSources = ["blue.mp3", "cigar.mp3", "immigrant.mp3", "monkey.mp3", "money.mp3"];
const player = document.getElementById("player");
function playAudio() {
let audioSource = audioSources[Math.floor(Math.random() * audioSources.length)];
player.src = audioSource;
};
player.addEventListener('ended', playAudio);
playAudio(); // start audio playing immediately
Tell me if that works.

Related

How to embed a youtube video in this javascript player?”

I need to put a YouTube video on this player where it is: https://www.w3schools.com/html/mov_bbb.mp4
I have to put a youtube video embed
I do not know how to do
I'm new to programming if anyone can help I'm struggling
<center><div id="myVideoSources" style="display:none;">
<source class="active" src="https://www.w3schools.com/html/mov_bbb.mp4" id="videoSource" type="video/mp4" startat="00:00:00" endat="00:00:10" name="Something" description="This is Gujarati Videol">
<source class="active" src="https://lh3.googleusercontent.com/lKr008DzBwztuG0f15-hzojP7ACJOlV10WrcFfhp9SWCok4igE4nT
tkCpcETaxvGF5m5tMgZPhkCPyiiueqcdV6d6yR3lM3ERPfRz5jkvrsM_y3xjq1o3GLnazLBEEOUaAbMS86y4g=m22" id="videosource2" type="video/mp4" startat="00:00:00" endat="03:02:02" name="PHP Video " description="This is PHP Video">
</div>
<video id="media-video" controls width="340" height="200"></video>
<script>
$(function () {
var sources = $("#myVideoSources source");
var jVideo = $("#media-video");
var currentVideoNum = 0;
loadNextVideo();
jVideo.bind("ended", function () {
loadNextVideo();
});
function loadNextVideo() {
var source = $(sources.get(currentVideoNum));
currentVideoNum++;
if(currentVideoNum >= sources.length) {
currentVideoNum = 0;
}
jVideo.html("");
jVideo.append(source);
var plainVideo = jVideo.get(0);
plainVideo.load();
plainVideo.play();
plainVideo.currentTime = getStartTime(source);
}
function getStartTime(source) {
var time = 0;
try {
var startAtStr = source.attr("startat");
time = startAtStr.split(":");
time = (time[0] * 3600) + (time[1] * 60) + (time[2] * 1)
} catch(e) {
console.log(e);
time = 0;
}
return time;
}
});
</script></center>

HTML5 audio playlist opens up new tab when clicked in Meteor web app

I'm working on a web app in meteor and I'm trying to use the HTML5, CSS and Javascript audio playlist in my app:
var audio;
var playlist;
var tracks;
var current;
init();
function init(){
current = 0;
audio = $('audio');
playlist = $('#playlist');
tracks = playlist.find('li a');
len = tracks.length - 1;
audio[0].volume = .10;
playlist.find('a').click(function(e){
e.preventDefault();
link = $(this);
current = link.parent().index();
run(link, audio[0]);
});
audio[0].addEventListener('ended',function(e){
current++;
if(current == len){
current = 0;
link = playlist.find('a')[0];
}else{
link = playlist.find('a')[current];
}
run($(link),audio[0]);
});
}
function run(link, player){
player.src = link.attr('href');
par = link.parent();
par.addClass('active').siblings().removeClass('active');
audio[0].load();
audio[0].play();
}
#playlist,audio{background:#666;width:400px;padding:20px;}
.active a{color:#5DB0E6;text-decoration:none;}
li a{color:#eeeedd;background:#333;padding:5px;display:block;}
li a:hover{text-decoration:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio id="audio" preload="auto" tabindex="0" controls="" type="audio/mpeg">
<source type="audio/mp3" src="http://www.archive.org/download/bolero_69/Bolero.mp3">
Sorry, your browser does not support HTML5 audio.
</audio>
<ul id="playlist">
<li class="active">Ravel Bolero</li>
<li>Moonlight Sonata - Beethoven</li>
<li>Canon in D Pachabel</li>
<li>patrikbkarl chamber symph</li>
</ul>
When I try to click on the li to play a song it opens the file up in a new tab with the audio in white and a black background.
I was wondering if anyone knew how to fix this as I've been stuck on this issue for almost three days now.
Thanks,
Dillon Davis
.I've just loaded jQuery in the snippet you've provided, and that worked fine. No other changes were required.
Check below snippet:
var audio;
var playlist;
var tracks;
var current;
init();
function init(){
current = 0;
audio = $('audio');
playlist = $('#playlist');
tracks = playlist.find('li a');
len = tracks.length - 1;
audio[0].volume = .10;
playlist.find('a').click(function(e){
e.preventDefault();
link = $(this);
current = link.parent().index();
run(link, audio[0]);
});
audio[0].addEventListener('ended',function(e){
current++;
if(current == len){
current = 0;
link = playlist.find('a')[0];
}else{
link = playlist.find('a')[current];
}
run($(link),audio[0]);
});
audio[ 0 ].addEventListener( 'canplay', function( e ) {
this.play();
}, false );
}
function run(link, player){
player.src = link.attr('href');
par = link.parent();
par.addClass('active').siblings().removeClass('active');
}
#playlist,audio{background:#666;width:400px;padding:20px;}
.active a{color:#5DB0E6;text-decoration:none;}
li a{color:#eeeedd;background:#333;padding:5px;display:block;}
li a:hover{text-decoration:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio id="audio" preload="auto" tabindex="0" controls="" type="audio/mpeg">
<source type="audio/mp3" src="http://www.archive.org/download/bolero_69/Bolero.mp3">
Sorry, your browser does not support HTML5 audio.
</audio>
<ul id="playlist">
<li class="active">Ravel Bolero</li>
<li>Moonlight Sonata - Beethoven</li>
<li>Canon in D Pachabel</li>
<li>patrikbkarl chamber symph</li>
</ul>
Update: I've added play() method after player loaded audio
Update 2: I've moved .play() to canplay event.

JS and JQuery Audio Volume Does Not Initialize

The Audio player loads and initializes, but the controls disappear once I pass the third song (see >= 3 test). I'm not certain if that's an incredible coincidence but it seems likely I have broken something. Why do the audio controls vanish?
Also, the volume controls do not initialize. Does anyone know why?
<script>
window.onload = function() {
var number = Math.floor((Math.random() * 10) + 1);
if(number >= 3) {
document.getElementById("audio").innerHTML = "<audio id='vid' src='remix.mp3' type='audio/mpeg' autoplay='true' loop='true'></audio>";
} else {
document.getElementById("audio").innerHTML = "<audio id='vid' src='lose.mp3' type='audio/mpeg' autoplay='true' loop='true'></audio>";
}
};
(function(){
var vid = document.getElementById("vid");
vid.volume = 0.2;
});
</script>
<script>
jQuery(function($) {
$("#vid").prop('volume', 0.2);
window.setVolume = function(bgAudio,vol) {
sounds[bgAudio].volume = 0.33;
}
});
</script>
<div id="audio">
</div>
There is no need to replace the whole audio tag. Just change the src attribute:
<audio id='vid' src='remix.mp3' type='audio/mpeg' autoplay='true' loop='true'></audio>
...
$('#vid').attr('src', 'remix.mp3');
EDIT
Your code is a mess, I've tried to refactor it a bit:
(function() {
var number = Math.floor((Math.random() * 10) + 1);
var player = $('#vid');
player.attr('src', number >= 3 ? 'remix.mp3' : 'lose.mp3');
player.prop('volume', '0.2');
player[0].play(); //run the audio track
//not sure about this function
window.setVolume = function(bgAudio, vol) {
sounds[bgAudio].volume = vol;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<audio id='vid' src='' type='audio/mpeg' loop='true'></audio>
And check mp3 file names and location.

Playlist with <audio> JavaScript

I'm creating a personal small website and I want to play some songs on it. What I've tried to do is the following:
<script type="text/javascript">
var i=1;
var nextSong= "";
var audioPlayer = document.getElementById('audio');
audioPlayer.onended = function(){
i++
nextSong = "Music/"+i+".mp3";
audioPlayer.src = nextSong;
audioPLayer.load();
audioPlayer.play();
if(i == 37) // this is the end of the songs.
{
i = 1;
}
}
</script>
<audio id="audio" src="Music/1.mp3"controls="controls" autoplay="autoplay" align=""> </audio>
However, I can't get this to work. It just plays the first song and doesn't execute the JS. I've tried alerting the state of i for example but it doesn't do anything.
Try this:
<script type="text/javascript">
var i=1;
var nextSong= "";
function setup() {
document.getElementById('audio').addEventListener('ended', function(){
i++;
nextSong = "Music/"+i+".mp3";
audioPlayer = document.getElementById('audio');
audioPlayer.src = nextSong;
audioPLayer.load();
audioPlayer.play();
if(i == 37) // this is the end of the songs.
{
i = 1;
}
}, false);
}
</script>
<body onLoad="setup();">
<audio id="audio" src="Music/1.mp3"controls="controls" autoplay="autoplay" align=""> </audio>
</body>
Amendment needed on this answer. You need to also identify the audio player, otherwise this won't work...
<script type="text/javascript">
function setup() {
var i=1;
var nextSong= "";
audioPlayer = document.getElementById('audio');
document.getElementById('audio').addEventListener('ended', function(){
i=i+1;
nextSong = "m"+i+".mp3";
audioPlayer.src = nextSong;
audioPlayer.load();
audioPlayer.play();
}, false);
}
</script>
<body onLoad="setup();">
<audio id="audio" src="m1.mp3" controls="controls" autoplay="autoplay" align=""> </audio>
</body>
var i=1; var nextSong= ""; function setup() { document.getElementById('audio').addEventListener('ended', function(){ i++; nextSong = "Music/"+i+".mp3"; audioPlayer = document.getElementById('audio'); audioPlayer.src = nextSong; audioPLayer.load(); audioPlayer.play(); if(i == 37) // this is the end of the songs. { i = 1; } }, false); }

calling the next item in my array

right now I have an array of videos. How do I make it so when i click next and prev the next or previous video in the array loads.
<video id="video" controls autoplay width="1000">
<source src="videos/test.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
<source src="videos/test.ogv" />
</video>
next
<script>
var vidURL=["videos/test.ogv","videos/test2.ogv","videos/test3.ogv","videos/test4.ogv","videos/test5.ogv" ]; // literal array
function vidSwap(vidURL) {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.src = vidURL;
myVideo.load();
myVideo.play();
}
Using yout code, it'll be something like this.
What you need to do is have the video that you loaded on a javascript variable.
Then, when you click prev or next you can call a function that will put the correct video number and call it.
<script>
var vidURL=["videos/test.ogv","videos/test2.ogv","videos/test3.ogv","videos"]
var video = 0;
function vidSwap() {
var myVideo = document.getElementsByTagName('video')[video];
myVideo.src = vidURL[video];
myVideo.load();
myVideo.play();
}
function prevVideo() {
if(video == 0) {
video = vidUrl.length;
}
else {
video -= 1;
}
vidSwap();
}
function nextVideo() {
if(video == length) {
video = 0;
}
else {
video += 1;
}
vidSwap();
}
</script>
<video id="video" controls autoplay width="1000">
<source src="videos/test.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
<source src="videos/test.ogv" />
</video>
prev
next
Introduce variable which will save current video index, then increment it or decrement it each time you press next/prev
</script>
var i = 0;
<script>
javascript:vidSwap(vidURL[i++])
It looks like you're missing another plus sign in your increment operator.
Try changing
next
To this
next
Wrapped up alternative with wrap-around;
next
prev
...
var Vids = (function() {
var _currentId = -1;
var _urls = ["videos/test.ogv","videos/test2.ogv","videos/test3.ogv","videos/test4.ogv","videos/test5.ogv" ]; // literal array
return {
next: function() {
if (++_currentId >= _urls.length)
_currentId = 0;
return this.play(_currentId);
},
prev: function() {
if (--_currentId < 0)
_currentId = _urls.length - 1;
return this.play(_currentId);
},
play: function(id) {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.src = _urls[id];
myVideo.load();
myVideo.play();
return false;
}
}
})();

Categories