Javascript: play a random song from an array (list) - javascript

I want to play a random song in a website. The tunes are short (max a few seconds, they don't need preload or buffering).
This part works, the number of songs may be unlimited, because tunes.length automatically counts all songs.
document.write displays the URL of a random song URL on the screen
tunes = new Array(
'"http://example.net/abcd.ogg"',
'"http://example.net/efgh.ogg"',
'"http://example.net/ijkl.ogg"'
)
var audiopath = (tunes[Math.floor(Math.random() * tunes.length)])
document.write (audiopath)
This part works too, when the URL is defined as a constant.
var song = new audio('http://example.net/abcd.ogg');
song.play();
When I try to replace the constant URL with the variable audiopath, it fails to play.
May it be anything wrong with the syntax?
I tried to run it with and without single quotes in the URL '"http://example.net/ijkl.ogg"' or "http://example.net/ijkl.ogg"
var song = new audio(audiopath);
song.play();

It might be better to handle starting playback once the song has fully loaded. Something like this:
let loaded = false;
const song = new Audio();
song.addEventListener('loadeddata', function()
{
loaded = true;
song.play();
}, false);
song.addEventListener('error' , function()
{
alert('error loading audio');
}, false);
song.src = tunes[Math.floor(Math.random() * tunes.length)];

Related

Play random sound on button that is spammable

I have a problem that i want to have a button, that plays random sound after I press it, but the other thing is that i want to spam the button and so does the sound. What I mean is that i dont want to wait for the sound to finish to play it again and like have 5 sounds or more playing depending on your click speed.
for(var i=0;i<1;i++)
{
document.getElementById("MyAudio.mp3")[i].addEventListener("click",function(){});
}
function playAudio()
{
var audio = new Audio("MyAudio.mp3");
audio.play();
}
<button onlick="playAudio()"></button>
That sounds fun and there's many ways to do it. I think the easiest way would be to pre-load the songs ahead of time and randomize it.
// Your sounds
let sounds = [new Audio('https://download.samplelib.com/mp3/sample-3s.mp3'), new Audio('https://download.samplelib.com/mp3/sample-6s.mp3'), new Audio('https://www.soundjay.com/human/fart-01.mp3')];
let lastSound = 0; // Not necessary but we don't want overlapping tracks.
// Listen for click on button (ID soundmachine)
// pointerdown is more suitable so adjusted it.
document.querySelector("#soundmachine1").addEventListener("pointerdown", () => {
// This is a small fix to allow the sound to be spammable and clear last track.
sounds[lastSound].pause();
sounds[lastSound].currentTime = 0;
let random = Math.floor(Math.random() * sounds.length);
sounds[random].play();
lastSound = random; // For the next click we want to cancel this sound if it's playing.
console.log(lastSound); // Just so you can see it count/play
});
document.querySelector("#soundmachine2").addEventListener("pointerdown", () => {
// Play till completed
let random = Math.floor(Math.random() * sounds.length);
sounds[random].play();
});
<button id="soundmachine1">click me ver1</div>
<button id="soundmachine2">click me ver2</div>
Something like this!
There's some odd things going on with this code, so let's rethink it from the beginning. First of all, you want to create an onclick handler on your button that plays your mp3 file. Let's do that first:
let audio = new Audio("MyAudio.mp3");
document.querySelector("button").addEventListener("click", () => {
audio.play()
});
Now, it sounds like you want it to play from the beginning every time when clicked, and not wait till it completes (which is the default behavior). So we need to reset the playback every time you click.
let audio = new Audio("MyAudio.mp3");
document.querySelector("button").addEventListener("click", () => {
audio.currentTime = 0;
audio.play();
});
🎉 🎶
And your HTML can just look like this:
<button>Play</button>

How To Play Embedded Multiple Videos From Different Websites Back To Back When One Video Ends

I have an embedded playlist of video links from different websites like Dailymotion, YouTube, Vimeo, etc., that I would like to play back to back on a personal website that I am working on. I found a script on the internet that plays embedded videos from multiple websites, but it only plays one video randomly. I would like the script to play each video back to back once one video is finished playing, but since I have no skills whatsoever in javascript, I don't know how to adapt this script to meet my needs. Does anyone know how I can accomplish this? I would greatly appreciate any kind of help. Thanks! Here is the script:
<div id="random_player"></div>
<script>
var videos = ["https://www.dailymotion.com/embed/video/x7raxfh?queue-enable=false","https://ok.ru/videoembed/3188453542586","https://www.youtube.com/embed/X3wV5ydVewY" ];
window.onload = function () {
var playerDiv = document.getElementById("random_player");
var player = document.createElement("IFRAME");
var randomVideoUrl = videos[Math.floor(Math.random() * videos.length)];
player.setAttribute('width', '640');
player.setAttribute('height', '390');
player.setAttribute('src', randomVideoUrl);
playerDiv.appendChild(player);
};
</script>
Follow the step by step code below-
Step 1
Copy paste the below code in html file by replacing url to your desired one!-
<iframe src="url" id="videoPlayer" height="200"">
Step 2
Javascript file should look like this-
let videoSource = new Array();
videoSource[0] = 'https://www.dailymotion.com/embed/video/x7raxfh?queue-enable=false","https://ok.ru/videoembed/3188453542586';
videoSource[1] = 'https://www.youtube.com/embed/X3wV5ydVewY4';
let i = 0; // global
const videoCount = videoSource.length;
const element = document.getElementById("videoPlayer");
function videoPlay(videoNum) {
element.setAttribute("src", videoSource[videoNum]);
element.autoplay = true;
element.load();
element.play();
}
document.getElementById('videoPlayer').addEventListener('ended', myHandler, false);
videoPlay(0); // play the video
function myHandler() {
i++;
if (i == videoCount) {
i = 0;
videoPlay(i);
} else {
videoPlay(i);
}
}
Step 3
Save the file and call the javascript file on html file. Open the html file in browser and it will run according to your asked question!

How can I play different sound files on click?

I built a simple matching game and added audio files for several cards like this:
cardList.map((cardItem) => {
var card = document.createElement("li");
card.classList.add("card");
var img = document.createElement("img");
img.src = [cardItem.img]
card.appendChild(img);
//audio starting here
audio = new Audio(cardItem.sound);
card.appendChild(audio);
audio.id += ' ' + cardItem.card;
deck.append(card);
card.className += ' ' + cardItem.name;
});
}
And in my startGame() function I added an eventListener to add audio.play(); on click.
So now, when I open dev tools, I can see audio elements for my cards but when I try and click on them, I'm only ever getting one audio file for all cards and not the audios I actually added to that specific element.
That's my GitHub file: https://github.com/cMikolai/guitar-colour-system-game/blob/master/js/app.js
Could anybody try and help me figure out how I could play the sound I added to the card I am clicking on?
I downloaded your code and played around. The code for playing audio is in the function startGame() in your app.js file.
app.js:
audio = []; // local variable declaration
...
...
// some code
function startGame() {
// some code
for (var i = 0; i < clickedCard.length; i++) {
clickedCard[i].addEventListener("click", function( event ) {
this.classList.add("open", "show");
openCards.push(this.getAttribute("class"));
audio.load();
audio.play(); // this is the line playing the audio
matchCards();
starRating();
}, false);
}
}
As you can see, you are not playing audio from the selected card but from the local variable audio.
So, you have to identify the selected card and play its respective audio instead of playing audio from the local variable.

if ("i am on this html page") { play this music};

if ("I am on this html page") {play this music};
Are there any commands to make this possible using Javascript?
this code worked for me :)
var soundEfx2 = document.getElementById("soundEfx2");
var soundMain = "Music/Main.mp3";
if(window.location.href.split('/').pop() == "Game2.html") {
soundEfx2.src = soundMain;
soundEfx2.play();
soundEfx2.loop = true;
}
Let's say that your URL is http://foo.com/bar.html.
With window.location.href you're getting the whole URL (http://foo.com/bar.html), but you only need to get the last URL segment (bar.html) of that URL, so use:
if(window.location.href.split('/').pop() == "Game2.html"){
// rest of code
}
if(window.location.href=='THIS_URL'){
//play the song
}
you can play it via jquery by getting the player id and calling the appropriate function and you can render the player by opening the php tags and echoing the PLAYER code.

How to repeat a song by Soundcloud API

I am making a custom music player based on SoundCloud API. I want to have a repeat button so when it is pressed, the current song will be repeated. SoundCloud does not provide any repeat method as far as I know, but it has some position() methods that get the corrent position of the song. I could not make this method working. But do you have any suggestion for repeating the current stream song ?
my code so far:
function playIt(){
var sound = SC.stream("/tracks/293", function(sound){
sound.play();
});
}
function repeat(){
var sound = SC.stream("/tracks/293", function(sound){
console.log(sound.position);
});
}
Demo: http://jsfiddle.net/danials/zcN7G/23/
Any idea?
Thanks in advance
var repeatSong = function() {
this.play({onfinish: repeat});
};
var sound = SC.stream("/tracks/293", function(sound){
sound.play({onfinish: repeatSong});
});
http://jsfiddle.net/G5RdX/1/

Categories

Resources