Run function after audio is loaded - javascript

I want to run a function after checking if an audio file is downloaded.
My js:
// https://freesound.org/people/jefftbyrd/sounds/486445/
var audioFile = "https://raw.githubusercontent.com/hitoribot/my-room/master/audio/test/test.mp3";
var audioElem = document.querySelector("audio");
var startElem = document.querySelector("button");
var resultScreen = document.querySelector("p");
function checkAudio() {
audioElem.setAttribute("src", audioFile);
if (audioElem.complete) {
resultScreen.innerHTML = "loaded audio";
}
}
startElem.addEventListener("click", function(){
checkAudio();
});
Codepen: https://codepen.io/carpenumidium/pen/KKPjRLR?editors=0011
I want the "loaded audio" text to be displayed, after the audio file has completed downloading. The code to check if the file has completed downloading might be utter bs so please go easy on me.
Thanks for your help!

You are not using the correct even to check the loaded status. See below a snippet that will do that.
You need to use the canplaythrough event that means
The browser estimates it can play the media up to its end without
stopping for content buffering.
The event you are using complete is actually triggered when
The rendering of an OfflineAudioContext is terminated.
// https://freesound.org/people/jefftbyrd/sounds/486445/
var audioFile = "https://raw.githubusercontent.com/hitoribot/my-room/master/audio/test/test.mp3";
var audioElem = document.querySelector("audio");
var startElem = document.querySelector("button");
var resultScreen = document.querySelector("p");
function checkAudio() {
audioElem.setAttribute("src", audioFile);
audioElem.addEventListener('canplaythrough', (event) => {
resultScreen.innerHTML = "loaded audio";
});
}
startElem.addEventListener("click", function() {
checkAudio();
});
<audio controls="controls" src=""></audio>
<button>load audio</button>
<div class="result">
<h1>Audio file status:</h1>
<p></p>
</div>
For more on audio elements refer MDN Docs
Hope this helps :)

You can use the onload event to get notified when the full audio is loaded:
function checkAudio() {
audioElem.setAttribute("src", audioFile);
audioElem.onload= ()=>{
resultScreen.innerHTML = "loaded audio";
}
}
startElem.addEventListener("click", function(){
checkAudio();
});

Related

Why the sound not working when the page is loaded?

I tried to play sound when the page is loaded, but it's not working never but when I click on button the sound is working.
JavaScript
<script>
$( document ).ready(function() {
let audio = new Audio('sounds/sound.mp3');
let is_play = true;
let btn = document.getElementById("sound_btn");
audio.play();
$("#" + btn.getAttribute("id")).click(function () {
if (is_play) {
btn.innerText = "Play Sound";
is_play = false
audio.pause();
} else {
btn.innerText = "Pause Sound";
is_play = true;
audio.play();
}
});
});
</script>
You’re probably using Google chrome which prevents playing audio files upon loading, you can check your log for such an error.
Audio files has to has to be played after a user’s event (as clicking).

Can I trigger a function when a audio object begins to play?

I have an <audio> object that might need to load before it can play, is there a way to trigger a function when either the sound begins after downloading, or when the user clicks the play button?
There is a playing event you can listen to like so.
audio.addEventListener("playing", function() {
console.log("playing");
});
http://w3c.github.io/html/semantics-embedded-content.html#eventdef-media-playing
Yes, there is onplay event for audio and video, you should use <audio> tag to do it
var audio = document.getElementById("Your_audio");
audio.onplay = function() {
//your code
};
with the javascript audio object you can add some event listener, like :
var horn = new Audio('car_horn.wav');
horn.addEventListener('loadeddata', () => {
let duration = horn.duration;
// The duration variable now holds the duration (in seconds) of the audio clip
})
as you can see here : https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement
you can simply add an evenListner like this:
<audio|video onplay="myScript">
e.g. you can do like this:
var aud = document.getElementById("myAudio");
aud.onplay = function() {
alert("The audio has started to play");
};

Autoplay within HTML

I am new to Javascript... like super new :X and i am writing my very first script to try and automate video episodes of my favorite anime because the videos on the site don't have a autoplay feature after you click the link. I read about Video and Var = 'My video' to try and figure out how to tell the script, when page loads video .autoplay = true...but i just get to dead ends. here is where i am at:
var urlsToLoad = [
'http://Site1/Ep1',
'http://Site1/Ep2',
'http://Site1/Ep3',
'http://Site1/Ep4'
];
if (document.readyState == "complete") {
FireTimer ();
}
window.addEventListener ("hashchange", FireTimer, false);
function FireTimer () {
setTimeout (GotoNextURL, 5000); // 5000 == 5 seconds
}
function GotoNextURL () {
var numUrls = urlsToLoad.length;
var urlIdx = urlsToLoad.indexOf (location.href);
urlIdx++;
if (urlIdx >= numUrls) urlIdx = 0;
Once the first video link starts 'Site1/EP1', i have this going:
function myFunction() {
var vid = document.getElementById("925664"); <--Ctrl+F 'Videoid' from Source
vid.autoplay = true;
vid.load();
}
but it just stays died like 'click play to start' ..
I can really use help here PLZZZ and thank you.
Something like this:
<!-- HTML Page -->
<video id="925664"></video>
// Javascript
function myFunction() {
var vid = document.getElementById("925664"); // <--Ctrl+F 'Videoid' from Source
vid.src = "path/to/file.mp4";
//vid.autoplay = true; // not really anything that's useful
vid.load();
vid.play();
}
Warning: Most mobile devices don't allow media files to play via code and require human interaction (click/touch) in order to start playback. However, on desktops this isn't a problem.
Try using the play() method instead.
function myFunction() {
var vid = document.getElementById("925664");
vid.play();
}

Processor Audio JavaScript HTML5

There is a js-script:
<script>
function start1() {
var audio = new Audio();
audio.src = URL.createObjectURL(document.getElementById('f1').files[0]);
audio.autoplay = true;
}
function start2() {
var audio = new Audio();
audio.src = URL.createObjectURL(document.getElementById('f2').files[0]);
audio.autoplay = true;
}
...
function stop() {
var audio = new Audio();
audio.stop();
}
</script>
and html code:
<body>
<input type="file" id="f1"></input>
<input type="file" id="f2"></input>
...
<button onmousedown="start1()" onmouseup="stop()">1</button>
<button onmousedown="start2()" onmouseup="stop()">2</button>
...
As can be understood through the script, he plays a sound file that loads by using the form files.
But there are two problems:
1) requires that sound is played only during events pressing (onmousedown) and stops when the mouse button is released (onmouseup).
Now the sound is played to the end it does not matter whether you clicked the mouse button and let go of it (because there is no test for this condition).
2) also need to create a simplified version of the script, as the functions for processing should be 16 pieces, but not manually register the same each function. You must create a generated script that will process the N-number of id (start1, start2, etc., f1, f2, etc).
Help to modify the code, you can also fully code jquery. It is not critical.
Thank you.
You can use local variables, you just need an identifier to find the audio element later. You also need to append the audio element to the DOM.
Also, you have to use pause() not stop().
<script>
function start(id, source) {
var aud = document.getElementById(id);
if (aud) {
aud.parentNode.removeChild(aud);
}
var audio = new Audio();
audio.setAttribute("id", id);
audio.src = URL.createObjectURL(document.getElementById(source).files[0]);
document.body.appendChild(audio);
audio.autoplay = true;
}
function stop(id) {
var aud = document.getElementById(id);
aud.pause();
}
</script>
<input type="file" id="f1"></input>
<input type="file" id="f2"></input>
<button onmousedown="start('1', 'f1')" onmouseup="stop('1')">1</button>
<button onmousedown="start('2', 'f2')" onmouseup="stop('2')">2</button>
This should work (Untested):
<script>
var a1 = new Audio();
var a2 = new Audio();
function start1() {
a1.src = URL.createObjectURL(document.getElementById('f1').files[0]);
a1.autoplay = true;
}
function start2() {
a2.src = URL.createObjectURL(document.getElementById('f2').files[0]);
a2.autoplay = true;
}
function stop() {
a1.stop();
a2.stop();
}
</script>

dynamically load src for audio and stop after src does not exist

I have songs called *song_1*, *song_2*, *song_3* etc. I want them to play immediately after the previous has finished. That's why I have an "ended" function which plays the next song automatically (works fine so far). The amount of songs I have is obtained dynamically, so I can't tell to stop loading the next src by hardcoding. But when a src does not exist, I get an error, and I cannot replay the songs after finishing etc. How can I prevent this error?
HTML:
<audio id="audio">
<source id="mp3Source" type="audio/mp3" />
</audio>
JQuery:
var audio = $("#audio");
var src = "audio/song_";
var countSongs = 0;
audio.addEventListener("ended", function() {
countSongs++
$('#mp3Source').attr('src', src+countSongs.toString()).detach().appendTo(audio);
audio.play();
});
$('#mp3Source').error(function() {
alert("error");
});
Try this. Getting the native DOM element as jQuery knows nothing about .play() method on the wrapped array returned by the $('#audio') selector:
var audio = $("#audio");
var src = "audio/song_";
var countSongs = 0;
audio.addEventListener("ended", function() {
countSongs++
$('#mp3Source').attr('src', src + countSongs.toString()).detach().appendTo(audio);
audio[0].play();
});
You seem to be a little confused regarding jQuery objects and DOM elements?
$('#audio') probably doesn't have an addEventListener method or a play method, so I'm suprised if that works at all ?
I would suggest something more like
var audio = $("#audio");
var src = "audio/song_";
var countSongs = 0;
audio.on({
ended: function() {
$('#mp3Source').prop('src', src + (++countSongs))
.detach()
.appendTo(audio);
this.load();
this.play();
},
error: function(e) {
alert( JSON.stringify(e) ); // for no console
$(this).off('ended');
}
});

Categories

Resources