Audio having a weird behaviour while being played - javascript

I have a problem with playing audio when I press or click a button.
Drum Machine
It seems like my audio has a delay but I put a audio.currentTime = 0, so I don't know what's going on.
Here is my JS:
const $ = document.querySelectorAll.bind(document);
const sounds = [
{id:'Bass Drum', letter:'Q', src:'https://dight310.byu.edu/media/audio/FreeLoops.com/3/3/Free%20Kick%20Sample%2011-909-Free-Loops.com.mp3'}
];
let volumeVal = 0.5;
$('input[type=range]')[0].addEventListener('input', function(e) {
volumeVal = e.target.value / 100;
});
function main(url, name) {
const audio = new Audio(url);
audio.currentTime = 0;
audio.preload = "auto";
audio.volume = parseFloat(volumeVal);
audio.play();
$('.name')[0].textContent = name;
}
window.onkeydown = function(e) {
function seter(id) {
setTimeout(() => {
$(`.${id}-but`)[0].classList.add('pressed');
setTimeout(() => {
$(`.${id}-but`)[0].classList.remove('pressed');
}, 140);
}, 0);
}
switch(e.key) {
case 'q':
main(sounds[0].src, sounds[0].id);
seter('q');
break;
}
}
$('.q-but')[0].addEventListener('click', () => {
main(sounds[0].src, sounds[0].id);
});

First off, big thanks to #Seblor for providing me with the solution.
I solved my problem by creating audio node for each sound:
<audio id="bass" preload="auto" src="https://dight310.byu.edu/media/audio/FreeLoops.com/3/3/Free%20Kick%20Sample%2011-909-Free-Loops.com.mp3"></audio>
And inside my JS file I added this event listener for every button:
$('.q-but')[0].addEventListener('click', () => {
const audio = $("#bass")[0];
audio.currentTime = 0;
audio.play();
});
Of course, now I could make my code less repetitive because I am doing this for all 9 buttons. And eventually I will.

Related

Javascript Refresh page audio play not working

Hi this my simple project
window.addEventListener("load", () => {
loadIndexedDB(1, callBackData);
loadNotesIndexedDB(callBackNotes);
});
let playSound = () => {
const audio = new Audio();
audio.src = "./audio/audio.wav";
audio.play();
audio.load();
};
let callBackNotes = (note) => {
const notes = [];
notes.push(note);
notes.forEach((el) => {
$(".note_empty").addClass("note_activ");
let dateForDateTimeLocal = dateFormat();
let alarmColor;
if (el.alarm != null && dateForDateTimeLocal < el.alarm) {
alarmColor = "#fff";
} else if (el.alarm != null && dateForDateTimeLocal >= el.alarm) {
alarmColor = "#ff1c1c";
playSound();
} else {
alarmColor = "#fff";
}
$(".add_note_container").append(
appendHtml(
el.noteBackColor,
el.noteTextColor,
el.note,
el.projectType,
el.time,
el.id,
el.alarm,
alarmColor
)
);
});
};
My project localhost start audio play working but refresh window or reload not working audio.play I am dont understand what the problem Please help me Thanks

Audio onended not functioning

The audio plays when the user interacts with the window however when the audio ends it doesnt log 'audio ended'
let audio = new Audio();
window.onclick = () => {
if (audio.paused) pickMusic().play();
};
audio.onended = () => {
console.log("audio ended");
};
function pickMusic() {
switch (Math.floor(Math.random() * 1)) {
case 0:
return (audio = new Audio("/music/gorp.mp3"));
break;
case 1:
return (audio = new Audio("/music/gorp.mp3"));
break;
}
}
<p>Click anywhere!</p>
When you call new Audio(), it will override the previous audio which is already attached with onended event.
In this case, whenever you call new Audio(), you also need to initialize onended event once again
let audio = new Audio()
window.onclick = () => {
if (audio.paused) pickMusic().play();
};
function pickMusic() {
switch (Math.floor(Math.random() * 1)) {
case 0:
audio = new Audio("http://commondatastorage.googleapis.com/codeskulptor-assets/jump.ogg")
audio.onended = () => {
console.log("audio ended");
};
return audio;
case 1:
audio = new Audio("http://commondatastorage.googleapis.com/codeskulptor-assets/week7-brrring.m4a")
audio.onended = () => {
console.log("audio ended");
};
return audio;
}
}
<p>Click anywhere!</p>

How can I write this audio playing code nicer?

I want you to play it as many times as I click on it.
(1 sec long audio only.)
function a() {
var elem = document.getElementById('musicplay');
var audio = document.getElementById('music');
var playing = false;
elem.addEventListener('click', function () {
if (playing) {
audio.play();
} else {
audio.play();
}
playing = !playing;
});
}
function playMusic() {
let playBtn= document.getElementById('musicplay');
let audio = document.getElementById('music');
let playing = false;
playBtn.addEventListener('click', ()=> {
if (playing) {
audio.pause();
playing = !playing;
} else {
audio.play();
playing = !playing;
}
});
}

Why this JS code doesn't work on altervista?

The issue is simple: on jsfiddle work perfectly, not on altervista.
const box = document.querySelector('.box');
var audio = document.getElementById('audio');
box.addEventListener('click', e => {
e.target.classList.toggle('pause');
if (audio.paused) {
audio.play();
} else {
audio.pause();
}
});
to try it: https://jsfiddle.net/rezt5und/2/

Shuffle song when it ends - javascript html5

I have this code that randomizes and play a song from a list of them:
var sounds = [
"sounds/royksopp.mp3",
"sounds/9thwonder.mp3",
"sounds/thisbeat.mp3",
"sounds/mosdef.mp3",
"sounds/bewater.mp3",
"sounds/boutdre.mp3",
"sounds/masterflash.mp3",
"sounds/2ep.mp3",
"sounds/drewestcoast.mp3",
"sounds/poetry.mp3",
"sounds/mfdoom.mp3",
"sounds/dreams.mp3",
"sounds/oizo.mp3", ];
function StartOrStop(audioFile) {
srcAudio = sounds[Math.floor(Math.random() * sounds.length)];
var audie = document.getElementById("myAudio");
audie.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
if (audie.paused == false) {
audie.pause();
} else {
audie.src = srcAudio;
audie.play();
}
}
When the song stops playing, it restarts with th same one. How can I make it so when the music ends, it will grab a new song from my list and automatically play it?
The problem is that you are simply calling this.play() in your ended event listener. Instead, you should be updating the src attribute with the random choice of song with this.src = srcAudio, similar to how you are for the initial selection:
function StartOrStop(audioFile) {
srcAudio = sounds[Math.floor(Math.random() * sounds.length)];
var audie = document.getElementById("myAudio");
audie.addEventListener('ended', function() {
this.currentTime = 0;
this.src = srcAudio;
this.play();
}, false);
if (audie.paused == false) {
audie.pause();
} else {
audie.src = srcAudio;
audie.play();
}
}
Hope this helps! :)

Categories