Upong calling audioElement.duraion returns infinite in chromium based browsers but works find in firefox. The song is stored locally in the same directory.
console.log("Welcome to Spotify | clone");
let songIndex = 0;
const masterPlay = document.getElementById("masterPlay");
const progressBar = document.getElementById("progressBar");
const gif = document.getElementById("gif");
const audioElement=document.getElementById("song")
// let audioElement=new Audio('./1.mp3')
// Handeling play pause and click
masterPlay.addEventListener('click', () => {
if (audioElement.paused || audioElement.currentTime <= 0) {
audioElement.play();
masterPlay.classList.remove("fa-circle-play");
masterPlay.classList.add("fa-circle-pause");
gif.style.opacity = 1;
}
else {
audioElement.pause();
masterPlay.classList.remove("fa-circle-pause");
masterPlay.classList.add("fa-circle-play");
gif.style.opacity = 0;
}
});
//EventListeners
audioElement.addEventListener("timeupdate", () => {
progress = ((audioElement.currentTime / audioElement.duration) * 100);
progressBar.value = progress;
console.log(audioElement.currentTime)
});
Expectations:
It returns the duration of the autio track.
What I tried:
Different browsers. (Works fine on firefox based browsers.)
Different song. (I found that some songs don't work on chrome but on firefox everything works.)
Tried using HTML audio element. (The problem persists)
Tried using JS audio(). (The problem still exists)
At the end of the day I found out that it was a bug with VS code Live Preview extension from Microsoft
Related
I have a use case where we donot want the user who is taking a test get sleep timeout while in test which is of 3 hrs. I was looking at nosleep.js but i has cpu overuse problem as it was not working in windows.
I was wondering how test taking apps do it, also how youtube achieves this.
Any help on this is really appreciated
Wake Lock API arrives in Chrome 79. However none of the other browser support this as of now.
https://developers.google.com/web/updates/2019/12/nic79#wake-lock
YouTube handles this by simply playing video. When you play a video with sound in the browser, the browser requests a wake lock automatically so as not to interrupt the user.
It isn't clear from your question what your specific requirements are, but if playing a video is possible, try that.
So after dealing with the pain of this problem for nice afternoon. I'm posting my solution. I'm using modules so delete export statements if you're not. My goal was to minimize effect on battery. So I play empty video file (10 x 10px, 1 frame lenght with empty audio track) every 10 seconds. I play it for the first time when user first clicks so the browser will allow me to play it. There are still side effects though. I.e. in Safari, the audio icon will blink and on iPhone lockscreen, the page will be shown as the last one playing video/audio.
let noSleep = null
let video = null
// --- Public ---
export function activate() {
if (!noSleep) noSleep = new NoSleep()
}
export function deactivate() {
if (noSleep) {
noSleep.stop()
noSleep = null
}
}
// --- Private ---
class NoSleep {
constructor() {
this._noSleep = true
this._keepAwake()
}
stop() {
this._noSleep = false
}
async _keepAwake() {
while(this._noSleep) {
if (video) video.play()
document.body.innerHTML += "<br>Played"
await wait(10000)
}
}
}
window.addEventListener("click", function enable() {
window.removeEventListener("click", enable)
// Initialize video element
video = document.createElement("video")
video.setAttribute("playsinline", "")
// Add mp4 source
let source = document.createElement("source")
source.src = mp4Src
source.type = "video/mp4"
video.append(source)
// Add webm source
source = document.createElement("source")
source.src = webmSrc
source.type = "video/webm"
video.append(source)
// Play it as a result of user interaction
video.play()
document.body.innerHTML = "Activated"
activate()
})
function wait(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
const mp4Src = "data:video/mp4;base64,AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAyBtb292AAAAbG12aGQAAAAAAAAAAAAAAAAAAAPoAAAAGwABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAACSnRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAGwAAAAAAAAAAAAAAAQEAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAABoAAAgAAAEAAAAAAcJtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAAKxEAAAEgFXEAAAAAAAxaGRscgAAAAAAAAAAc291bgAAAAAAAAAAAAAAAENvcmUgTWVkaWEgQXVkaW8AAAABaW1pbmYAAAAQc21oZAAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAABLX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jjU1JTk9SX1ZFUlNJT05Eh4EwZ8gBAAAAAAAAG0WjkUNPTVBBVElCTEVfQlJBTkRTRIeEcXQgIGfIAQAAAAAAABlFo4hUSU1FQ09ERUSHizAwOjAwOjAwOjAwZ8gBAAAAAAAAKkWjn0NPTS5BUFBMRS5RVUlDS1RJTUUuRElTUExBWU5BTUVEh4VlbXB0eWfIAQAAAAAAACRFo5lDT00uQVBQTEUuUVVJQ0tUSU1FLlRJVExFRIeFZW1wdHlnyAEAAAAAAAAaRaOHRU5DT0RFUkSHjUxhdmY1OC43Ni4xMDBzcwEAAAAAAACxY8CLY8WIx4eCZsaZtwtnyAEAAAAAAAAiRaOMSEFORExFUl9OQU1FRIeQQ29yZSBNZWRpYSBBdWRpb2fIAQAAAAAAABtFo4lWRU5ET1JfSUREh4xbMF1bMF1bMF1bMF1nyAEAAAAAAAAjRaOHRU5DT0RFUkSHlkxhdmM1OC4xMzQuMTAwIGxpYm9wdXNnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjAzNDAwMDAwMAAAH0O2daTngQCjh4EAAID8//6gAQAAAAAAAA+hh4EAFQD8//51ooNwiJgcU7trkbuPs4EAt4r3gQHxggMY8IED"
Implementation is made so multiple calls to activate()/deactivate() have no effect (which was beneficial in my use case). I create NoSleep object to make sure that it's gonna deactivate (operation may take up to 10 seconds to deactivate). Without it quick successive activations and deactivations could result in multiple wake cycles to run at the same time without quiting themselves eventually.
Play looped VIDEO or AUDIO on your page
You can use this a quick example to add a Fake looped video to your page and prevent mobile device from sleep:
// Create the root video element
var video = document.createElement('video');
video.setAttribute('loop', '');
// Add some styles if needed
video.setAttribute('style', 'position: fixed;');
// A helper to add sources to video
function addSourceToVideo(element, type, dataURI) {
var source = document.createElement('source');
source.src = dataURI;
source.type = 'video/' + type;
element.appendChild(source);
}
// A helper to concat base64
var base64 = function(mimeType, base64) {
return 'data:' + mimeType + ';base64,' + base64;
};
// Add Fake sourced
addSourceToVideo(video,'webm', base64('video/webm', 'GkX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NiB9FAEQBFGMAAAGyTGF2YzUyLjg3LjQGAQIAAAAYc3R0cwAAAAAAAAABAAAAAQAAAAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAFHN0c3oAAAAAAAAAEwAAAAEAAAAUc3RjbwAAAAAAAAABAAAALAAAAGB1ZHRhAAAAWG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAK2lsc3QAAAAjqXRvbwAAABtkYXRhAAAAAQAAAABMYXZmNTIuNzguMw=='));
// Append the video to where ever you need
document.body.appendChild(video);
// Start playing video after any user interaction.
// NOTE: Running video.play() handler without a user action may be blocked by browser.
var playFn = function() {
video.play();
document.body.removeEventListener('touchend', playFn);
};
document.body.addEventListener('touchend', playFn);
I am making a web app that can be open for a long time. I don't want to load audio at load time (when the HTML gets downloaded and parsed) to make the first load as fast as possible and to spare precious resources for mobile users. Audio is disabled by default.
Putting the audio in CSS or using preload is not appropriate here because I don't want to load it at load time with the rest.
I am searching for the ideal method to load audio at run time, (after a checkbox has been checked, this can be after 20 minutes after opening the app) given a list of audio elements.
The list is already in a variable allSounds. I have the following audio in a webpage (there are more):
<audio preload="none">
<source src="sound1.mp3">
</audio>
I want to keep the same HTML because after second visit I can easily change it to (this works fine with my server-side HTML generation)
<audio preload="auto">
<source src="sound1.mp3">
</audio>
and it works.
Once the option is turned on, I want to load the sounds, but not play them immediately. I know that .play() loads the sounds. But I want to avoid the delay between pressing a button and the associated feedback sound.
It is better to not play sound than delayed (in my app).
I made this event handler to load sounds (it works) but in the chrome console, it says that download was cancelled, and then restarted I don't know exactly what I am doing wrong.
Is this is the correct way to force load sounds? What are the other ways? If possible without changing the HTML.
let loadSounds = function () {
allSounds.forEach(function (sound) {
sound.preload = "auto";
sound.load();
});
loadSounds = function () {}; // Execute once
};
here is playSound function, but not very important for the questions
const playSound = function (sound) {
// PS
/* only plays ready sound to avoid delays between fetching*/
if (!soundEnabled)) {
return;
}
if (sound.readyState < sound.HAVE_ENOUGH_DATA) {
return;
}
sound.play();
};
Side question: Should there be a preload="full" in the HTML spec?
See also:
Preload mp3 file in queue to avoid any delay in playing the next file in queue
how we can Play Audio with text highlight word by word in angularjs
To cache the audio will need to Base64 encode your MP3 files, and start the Base64 encoded MP3 file with data:audio/mpeg;base64,
Then you can pre-load/cache the file with css using something like:
body::after {
content:url(myfile.mp3);
display:none;
}
I think I would just use the preloading functionality without involving audio tag at all...
Example:
var link = document.createElement('link')
link.rel = 'preload'
link.href = 'sound1.mp3'
link.as = 'audio'
link.onload = function() {
// Done loading the mp3
}
document.head.appendChild(link)
I'm quite sure that I've found a solution for you. As far as I'm concerned, your sounds are additional functionality, and are not required for everybody. In that case I would propose to load the sounds using pure javascript, after user has clicked unmute button.
A simple sketch of solution is:
window.addEventListener('load', function(event) {
var audioloaded = false;
var audioobject = null;
// Load audio on first click
document.getElementById('unmute').addEventListener('click', function(event) {
if (!audioloaded) { // Load audio on first click
audioobject = document.createElement("audio");
audioobject.preload = "auto"; // Load now!!!
var source = document.createElement("source");
source.src = "sound1.mp3"; // Append src
audioobject.appendChild(source);
audioobject.load(); // Just for sure, old browsers fallback
audioloaded = true; // Globally remember that audio is loaded
}
// Other mute / unmute stuff here that you already got... ;)
});
// Play sound on click
document.getElementById('playsound').addEventListener('click', function(event) {
audioobject.play();
});
});
Of course, button should have id="unmute", and for simplicity, body id="body" and play sound button id="playsound. You can modify that of course to suit your needs. After that, when someone will click unmute, audio object will be generated and dynamically loaded.
I didn't try this solution so there may be some little mistakes (I hope not!). But I hope this will get you an idea (sketch) how this can be acomplished using pure javascript.
Don't be afraid that this is pure javascript, without html. This is additional functionality, and javascript is the best way to implement it.
You can use a Blob URL representation of the file
let urls = [
"https://upload.wikimedia.org/wikipedia/commons/b/be/Hidden_Tribe_-_Didgeridoo_1_Live.ogg"
, "https://upload.wikimedia.org/wikipedia/commons/6/6e/Micronesia_National_Anthem.ogg"
];
let audioNodes, mediaBlobs, blobUrls;
const request = url => fetch(url).then(response => response.blob())
.catch(err => {throw err});
const handleResponse = response => {
mediaBlobs = response;
blobUrls = mediaBlobs.map(blob => URL.createObjectURL(blob));
audioNodes = blobUrls.map(blobURL => new Audio(blobURL));
}
const handleMediaSelection = () => {
const select = document.createElement("select");
document.body.appendChild(select);
const label = new Option("Select audio to play");
select.appendChild(label);
select.onchange = () => {
audioNodes.forEach(audio => {
audio.pause();
audio.currentTime = 0;
});
audioNodes[select.value].play();
}
select.onclick = () => {
const media = audioNodes.find(audio => audio.currentTime > 0);
if (media) {
media.pause();
media.currentTime = 0;
select.selectedIndex = 0;
}
}
mediaBlobs.forEach((blob, index) => {
let option = new Option(
new URL(urls[index]).pathname.split("/").pop()
, index
);
option.onclick = () => console.log()
select.appendChild(option);
})
}
const handleError = err => {
console.error(err);
}
Promise.all(urls.map(request))
.then(handleResponse)
.then(handleMediaSelection)
.catch(handleError);
I'm working on my sandbox game and I started adding some sound effects..
The problem is, that the audio works fine on Edge, but when I'm trying it on chrome or opera the audio for (and only for) dirt starts very low and after few repeated plays of this sound effect it gets on normal sound volume (dirt0.volume always shows 1).. On edge it starts normally loud. Other sound effects are working fine even on chrome but i noticed that the speed of repeating is a lot faster on chrome than on edge.. i din't know why but I want them to be equal on every browser..
I'm loading sound effects normally
like this:
grass0 = new Audio('grass0.wav');
grass1 = new Audio('grass1.wav');
dirt0 = new Audio('dirt0.wav');
dirt1 = new Audio('dirt1.wav');
wood0 = new Audio('wood0.wav');
wood1 = new Audio('wood1.wav');
and then im just playing them by using .play() if none
of the other sound effects are playing.
if(grass0.paused & grass1.paused & dirt0.paused & dirt1.paused & wood0.paused & wood1.paused){
if(blocks[i].id == 1){ //Blok [1]
if(audio[0] == 0){
grass0.play();
audio[0] = 1;
}else{
grass1.play();
audio[0] = 0;
}
}else if(blocks[i].id == 2){ //Blok [2]
if(audio[1] == 0){
dirt0.play();
audio[1] = 1;
}else{
dirt1.play();
audio[1] = 0;
}
}else if(blocks[i].id == 7){ //Blok [7]
if(audio[2] == 0){
wood0.play();
audio[2] = 1;
}else{
wood1.play();
audio[2] = 0;
}
}
}
..
Look at this video for better understanding.
I have a problem with playing base64 audio file on newest Chrome 46.0.2490.86 m
This audio file can play only 1 times. It doesn't play on second times.
We need to refresh browser to relay again.
This file played well on previous version of Chrome (can replay many times without refreshing browser).
This is my code:
window.playAudio1 = function () {
var audio = document.getElementById("audio");
audio.src = "<base64 mp3 audio>";
audio.play();
}
window.playAudio2 = function () {
var audio = document.getElementById("audio");
audio.src = "<base64 mp3 audio>";
audio.play();
}
JSFiddle
I encountered the same problem recently.
The only way i could get it to work was to include some random information in the base64 info.
e.g.
function beep()
{
try
{
var snd = new Audio("data:audio/wav;rnd=" + getRandom(1,100000) + ";base64,<<raw base64 data>>");
snd.load();
snd.currentTime = 0;
snd.play();
}
catch(e)
{
alert(e);
}
}
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
I also tried adding in the .load() and the .currentTime = 0, but to be honest, i don't think they are required for the fix, didn't try without though.
Enjoy!
In an English/Thai language web page, I've got 4 columns of English phrases with associated audio files. A phrase from each column is selected by mouse click. After 4 phrases have been selected, I want their audio files to play sequentially. Here is 1 of 4 segments of code doing the selection (they differ only in html tags selection and localStorage locations).These work OK.
var audioIsPlaying = false;
jQuery("div#wh_set1").on("click", "p span", function (evnt) {
var elementId = evnt.target.id,
word1 = jQuery(this).text();
jQuery("span#word1").html(word1);
var pathVar = document.getElementById("pathVar").innerHTML,
oggVar = pathVar+elementId+".ogg",
mp3Var = pathVar+elementId+".mp3";
if(Modernizr.audio.ogg) {
localStorage.setItem("wh_set1", oggVar);
}else {
localStorage.setItem("wh_set1", mp3Var);
}
});
Sequential playback of the audio files is intended to be handled by the following code:
var currentAudio = document.createElement('audio'), i ;
function audioPlay(i) {
audioIsPlaying = false;
currentAudio.setAttribute("src", localStorage.getItem('wh_set' + i));
currentAudio.load();
currentAudio.play();
audioIsPlaying = true;
// alert("wh_set" +i);
}
for(i = 1; i <= 4; i++) {
currentAudio.addEventListener("ended", audioPlay(i));
}
But this does not work as intended. Only the audio file of the last of the 4 selected phrases plays. If the alert is uncommented then each selection plays in the correct sequence. Similarly, if the code is stepped thru with Firebug, then the audio files play in correct sequence.
I've had a look at previous posts on audio file sequencing but I could see anything directly applicable. Any help would be much appreciated.
The problem is: you don't add function to event ended, you call it immediatly.
Your code do this:
audioPlay(1);
audioPlay(2);
audioPlay(3);
audioPlay(4);
The first three audios don't have a chance to load and start.
I replaced
for(i = 1; i <= 4; i++) {
currentAudio.addEventListener("ended", audioPlay(i));
}
to
var i = 1;
currentAudio.addEventListener( "ended", function() {
i++;
if ( i < 5 ) {
audioPlay( i );
}
} );
audioPlay( 1 );
and it works perfectly in Chrome and Firefox