Pick a random .mp3 file to autoplay from a list of urls on page load? - html

Right now I have this
<audio autoplay>
<!-- <source src="https://a.pomf.cat/vmrlef.mp3" type="audio/mpeg">--> <!-- escape through the snow -->
<!-- <source src="https://files.catbox.moe/vif2j1.mp3" type="audio/mpeg"> <!-- sea map -->
<source src="https://files.catbox.moe/4abc2w.mp3" type="audio/mpeg"> <!-- ミク - prblm- -->
</audio>
which I have no idea how to make it select each one randomly on page load up, is there a way to like have a list and then make source src choose from a list randomly on each reload? pretty new to html and any help would be much appreciated!! ^^

Like this
https://jsfiddle.net/mplungjan/6opnhymz/
const audioUrls = ["https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",
"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3",
"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3"];
const rnd = Math.floor(Math.random()*audioUrls.length); // random number from 0 to length of array
const audio = new Audio(); // an audio object
const loadedAudio = () => audio.play(); // what happens after the audio successfully has been found
document.body.appendChild(audio); // add it to the page
audio.addEventListener('canplaythrough', loadedAudio, false); // add the event that will play, here "can it play?"
console.log(`Playing #${rnd}:${audioUrls[rnd]}`); // for us to see it works
audio.src = audioUrls[rnd]; // actual trigger to play the audio
audio.load(); // iOS may need this

Related

How do I add looping on HTML5 audio?

I need help looping a HTML5 audio clip.
I have the below script, but it only plays once. I need it to play the music clip when the link is pressed and plays non-stop in a loop. The audio can only then be stopped when refreshing the page or but selecting the link again:
Link here
<script>
// Sound for background music
var html5_audiotypes={
"mp3": "audio/mpeg",
"mp4": "audio/mp4",
"ogg": "audio/ogg",
"wav": "audio/wav"
}
function createsoundbite(sound){
var html5audio=document.createElement('audio')
if (html5audio.canPlayType){ //check support for HTML5 audio
for (var i=0; i<arguments.length; i++){
var sourceel=document.createElement('source')
sourceel.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i))
sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
html5audio.appendChild(sourceel)
}
html5audio.load()
html5audio.playclip=function(){
html5audio.pause()
html5audio.currentTime=0
html5audio.play()
}
return html5audio
}
else{
return {playclip:function(){throw new Error("")}}
}
}
//Initialize two sound clips with 1 fallback file each:
var mouseoversound=createsoundbite("music.ogg", "music.mp3")
var clicksound=createsoundbite("music.ogg", "music.mp3")
</script>
Thank you.
why don't you try using the audio tag and add the attribute loop so it would loop back to back
replace the src with your own audio file to see it looping
<h1>The audio loop attribute</h1>
<p>Click on the play button to play a sound:</p>
<audio controls loop>
<source src="https://www.w3schools.com/tags/horse.ogg" type="audio/ogg">
<source src="https://www.w3schools.com/tags/horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
click this link to see its working

HTML Auto-Play a song and StartAt

I have this code, but I do not know how to make the song start from 0:19 seconds. Could you help me out?
<div class="fin-subheading">
· ROLEPLAY ·
<audio id='music' volume='0.5' autoplay controls>
<source src="anonymous.mp3" type="audio/mpeg">
</audio>
</div>
<script>
var audio = document.getElementById("music");
audio.volume = 0.3;
</script>
You can specify a playback range in the src attribute itself. See the docs here:
When specifying the URI of media for an or element,
you can optionally include additional information to specify the
portion of the media to play. To do this, append a hash mark ("#")
followed by the media fragment description.
A time range is specified using the syntax:
#t=[starttime][,endtime]
So instead of:
<source src="anonymous.mp3" type="audio/mpeg">
simply put:
<source src="anonymous.mp3#t=n,m" type="audio/mpeg">
where n and m are the start and end times, respectively.
The range can also be unbounded as well. So you could, for instance do this:
<source src="anonymous.mp3#t=19" type="audio/mpeg">
which will start at 19 seconds and play through till the end; or even this:
<source src="anonymous.mp3#t=,19" type="audio/mpeg">
which will start from the beginning through 19 seconds.
You can use currentTime property
window.onload = function() {
const audio = document.getElementById("music");
audio.volume = 0.3;
audio.currentTime = 19;
audio.play();
}
You need to use canplaythrough event and within that currentTime and then play when that time is reached.
Make sure you do not autoplay in the audio tag in HTML.
<audio id="audio2"
preload="auto"
src="http://upload.wikimedia.org/wikipedia/commons/a/a9/Tromboon-sample.ogg" >
<p>Your browser does not support the audio element</p>
</audio>
<script>
myAudio=document.getElementById('audio2');
myAudio.addEventListener('canplaythrough', function() {
this.currentTime = 19;
this.play();
});
</script>

Angular 8 - Is there a way to bind to a video element to determine when it is loaded/starts playing?

Given:
<video poster="assets/videos/poster.png"
#videoPlayer
onloadedmetadata="this.muted = true">
<source src="assets/videos/video.mp4" type="video/mp4">
</video>
And in Angular:
...
public videoLoaded: boolean = false;
...
How can I bind videoLoaded to update once the video starts playing? (or is loaded) I've looked online and saw some older jquery implementations that seem to not be working in newer versions of chrome and want to know the latest way on how to accomplish this
Thanks
What you could do is make a reference to the video player itself with Angular's ViewChild and check if it's clicked.
#ViewChild('videoPlayer') videoPlayer: ElementRef;
videoClicked = false;
startVideo(): void {
this.videoClicked = true;
this.videoPlayer.nativeElement.play();
}
The startVideo() method will be used inside the HTML to trigger the change. The additional paragraph is used to see the change.
<video (click)="startVideo()" width="400"
#videoPlayer>
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
</video>
<p>Video clicked: {{videoClicked}}</p>
See this StackBlitz as an example of above behaviour.
Edit
A better way to do this is to use HTMLMediaElement's onplaying and loadeddata event. See MDN for documentation on onplaying and documentation on onplaying. In normal JavaScript it would look like this:
const video = document.querySelector('video');
video.onplaying = (event) => {
console.log('Video is no longer paused.');
};
In Angular, there are some small changes required. The HTML can stay pretty clean.
<video controls width="400"
#videoPlayer>
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
</video>
<p>Video loaded: {{dataLoaded}}</p>
<p>Video started: {{videoStarted}}</p>
The biggest changes are in the component, ngAfterViewInit checks if the element is there after view has been initialised. The loadeddata event is fired when the frame at the current playback position of the media has finished loading (so ready to play). Next to that, you can access the element's onplaying event to check if the video is not paused.
#ViewChild('videoPlayer') videoPlayer: ElementRef;
dataLoaded = false;
videoStarted = false;
ngAfterViewInit() {
this.videoPlayer.nativeElement.onloadeddata = (event) => {
console.log('Video data is loaded.');
this.dataLoaded = true;
};
this.videoPlayer.nativeElement.onplaying = (event) => {
console.log('Video is no longer paused.');
this.videoStarted = true;
};
}
Here's a StackBlitz example to show this example.
you can use HTML Audio/Video Events provided by html 5 video attribute.
loadeddata -> Fires when the browser has loaded the current frame of the audio/video
loadedmetadata -> Fires when the browser has loaded meta data for the audio/video
loadstart -> Fires when the browser starts looking for the audio/video

how to get html5 video total duration displayed without playing the video

I do found something online that is just about to be similar to what am trying to achieve, but here are a few problems i encountered. (1) i want the time be in minutes and seconds format. (2) the code only works for a single video in my html file. how can i make the code work for multiple videos in my file all showing their different durations. below is the code
<script> var myVideoPlayer = document.getElementById('video_player'), meta = document.getElementById('meta'); myVideoPlayer.addEventListener('loadedmetadata', function () { var duration = myVideoPlayer.duration; meta.innerHTML = "Duration is " + duration.toFixed(2) + " seconds." }); </script>
<video id="video_player" width="320" height="240" controls poster="something/something.jpg"> <source src="someVideo.mp4" type="video/mp4"> </video>
<div id="meta"></div>
This is what I want to achieve using codeigniter
Like this:
<video width="320" height="240" id = "myVideo" controls>
<source src="someVideo.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<script>
var e = document.getElementById("myVideo");
var cancelAlert = false;
var run = function() {
if (e.readyState === 4 && !cancelAlert) {//readyState 4 means it is loaded fully
cancelAlert = true;//This is so that it only alerts once. No spam pls.
alert(e.duration);
}
requestAnimationFrame(run);//This is so that it runs every frame.
};
run();//run the function
</script>
You may need to do some tweaking, and there is probably a more efficient way to do this, but this is what I do.

How to play an audio file in the background after clicking a link? (no embed)

Currently I am using following code to play some audio after a link is clicked:
Pronunciation of a word
For now if the user clicks on the link, a new page with an audio playing panel is loaded. After playing the audio, the user has to click GO BACK button of the browser to get back to the original content.
Is it possible to play the audio without being directed to a new page? When the user clicks on the link, the audio just plays in the background?
(Don't want to use embed because it's just a 1 second audio for a word's pronunciation as a minor explanation of an uncommon word).
Actually the href attribute is redirecting you to the new page, you can use e.prevenDefault() in the link click event handler to stop this redirection and create a dynamic audio element with this href as source and play it.
This is what you need:
function playItHere(e, link) {
var audio = document.createElement("audio");
var src = document.createElement("source");
src.src = link.href;
audio.appendChild(src);
audio.play();
e.preventDefault();
}
Pronunciation of a word
In html5, you can actually use the <audio> tag to get that done!
<audio src="/music/myaudio.ogg" autoplay> Sorry, your browser does not support the <audio> element. </audio>
SOURCE: Wired
If you use a tag be careful with href .
Code snippet fixed .
First you will need to make convert ogg to the mp3 and than use it for multi source .
Small browser detector (chrome/opera/safari - mp3 and mozilla - ogg . )
E("PLAYER").addEventListener("error", function(e) {
console.log("error: " + e.target.error)
});
function PLAYER_BACKGROUND(what) {
var SOURCE_PATH = E(what).getAttribute("whattoplay")
if (isChrome == true)
{
SOURCE_PATH = SOURCE_PATH.replace(".ogg" , ".mp3")
}
else {
SOURCE_PATH = SOURCE_PATH.replace( ".mp3" , ".ogg" )
}
E("PLAYER").src = SOURCE_PATH
E("PLAYER").play()
}
<script>
var E = function(id){return document.getElementById(id)};
var isChrome = /Chrome/.test(navigator.userAgent) || /Safari/.test(navigator.userAgent);
</script>
<a id="audio_1" onclick="PLAYER_BACKGROUND(this.id)" whattoplay="https://maximumroulette.com/framework/res/audio/laser7.ogg" href="javascript:void(0)">Pronunciation of a word</a>
<audio style="display:none" id="PLAYER" autoplay controls>
<source src="#" type="audio/ogg">
<source src="#" type="audio/mpeg">
Sorry, your browser does not support the element.
</audio>