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
Related
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
What I want to achieve: To stop a previously started sound when a new is started. What I have now: The sounds plays simultanously, none of them is stopping. The probably reason: Wrong logic statement in a line if (audio.played && audio.paused){. Before you judge me for not trying hard enough - I am trying to solve this from 3 days, I am a beginner. It should take me a few minutes, even an hour. I tried in several combinations.At the end I listed several websites which I tried and I still haven't solved it. In all answers is something similar but still I can't made a browser to chose, always only one part is executed either audio.play() or audio.pause() in the log. It works but not as I want and these logical statements are like on other informations on the forum. At the end of the message you can see all similar topics I already tried several times. I kept just as clear code as possible and I want to do it this way, in vanilla javascript because I won't deal for now with anything more complicated. An audio url is taken from modified id on click, the audios are on my disk. It works, I made some mistake in line if (audio.played && audio.paused){ Any ideas except giving up and changing a hobby?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Timeout</title>
</head>
<script>
function playAudio3(clicked_id) {
var OriginalID = (clicked_id);
var res = OriginalID.slice(5,-1);
var audioID=res+'.mp3';
var url =audioID;
var audio = new Audio(url);
if (audio.played && audio.paused){
audio.play();
console.log('audio.play was used.');
}else {
audio.currentTime = 0
audio.pause();
console.log('audio.pause was used.');
}
}
</script>
<body>
<span id="guita2x"onclick="playAudio3(this.id);"> Guitar. </span>
<span id="piano2x" onclick="playAudio3(this.id);"> Piano. </span>
<span id="basse15x" onclick="playAudio3(this.id);"> Basse. </span>
</body>
</html>
how do i stop a sound when a key is released in JavaScript
Javascript Audio Play on click
Javascript to stop playing sound when another starts
HTML5 Audio stop function
cancel an if statement if another statement comes true
Stopping audio when another audio file is clicked using jQuery while obscuring link
https://www.w3schools.com/jsref/dom_obj_audio.asp
HTML5 Audio pause not working
Never give up, and don't change a hobby. :)
Possible solution from one hobbyist, too:
files = ['guitar', 'piano', 'bass']; // name of your files in array. You can get this array from looping through your html/spans id's too, but, this is basic logic
audios = []; //empty audios object array
for (i = 0; i < files.length; i++) {
var audioID = files[i] + '.mp3';
var url = audioID;
var audio = new Audio(url);
audios.push(audio); //place all audio objects into array
}
console.log(audios);
//now - basic logic to check which audio element to play, and to stop others
function playAudio3(clicked_id) {
for (i = 0; i < audios.length; i++) {
if (audios[i].src.includes(clicked_id)) {
audios[i].play();
} else {
audios[i].currentTime = 0
audios[i].pause();
}
}
}
So, you are creating all audio objects at the page load, and then choose which one to play. Of course, this will play all audio files from the start. If you want to keep the track of the audio progress, and play it from the last pause, you will need some additions, but, this could be the start, i hope.
OK, updated, i kept some of your code, and slightly changed some things in HTML.
Your complete code now should look like this: (HTML)
<span class='aud' id="guita1x" onclick="playAudio3(this.id);"> Guitar. </span>
<span class='aud' id="piano2x" onclick="playAudio3(this.id);"> Piano. </span>
<span class='aud' id="basse3x" onclick="playAudio3(this.id);"> Basse. </span>
Js:
spans=document.querySelectorAll('.aud');
console.log(spans);
audios = []; //empty audios object array
for (i = 0; i < spans.length; i++) {
var OriginalID = spans[i].id;
var res = OriginalID.slice(5,-1);
var audioID=res+'.mp3';
var url =audioID;
var audio = new Audio(url);
audios.push(audio); //place all audio objects into array
}
console.log(audios);
//now - basic logic to check which audio element to play, and to stop others
function playAudio3(clicked_id) {
for (i = 0; i < audios.length; i++) {
clickid=clicked_id.replace(/[A-Za-z]/g,'')+'.mp3';
if (audios[i].src.includes(clickid)) {
audios[i].play();
} else {
audios[i].currentTime = 0
audios[i].pause();
}
}
}
Now, i have just added class 'aud' to your spans, for easier targeting.
Then, i have collected id's from the spans and placed it in the audios array. (Not sure why you are slicing names/ids, you can simplify things by adding just numbers: 1, 2, 3 and so on).
NOW, this MUST work, IF
you have 3 .mp3 files in the same folder as your html/js file, called: 1.mp3, 2.mp3, 3.mp3.
if you place your javascript bellow HTML, BEFORE closing 'body' tag.
I'm writing a choose your own adventure program where If a specific option is chosen (example to wait) the user gets a random number between 1-10 to do push ups(the push-ups would be the user clicking on the prompt "ok" button however many times the random number is equal to) here's my code so far but I keep getting errors. I'm a complete noob so go easy on me.
var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
alert("Nice! Lets see you crank out " + pushUp + "!");
setsOf10 = true;
}
for (var i=0; i<count; i++){
pushUps();
}
else {
alert("Really, thats it? Try again");
}
while ( setsOf10 == false);
}
After playing with this some more I can tell i'm close but still don't have it. and again, I'M NOT ASKING YOU TO SOLVE THIS FOR ME JUST NEED POINTERS AS TO WHAT IM DOING WRONG OR MISSING. Here's what I have, Its giving me my random number I just need it to allow me to click the "ok" button however many times the random number has assigned me.
var pushUpSets = Math.floor((Math.random() * 10) + 1);
function pushUps(){
alert(pushUpSets);
if (pushUpSets < 3){
var weak = "Thats it? Weak sauce!";
alert(weak);
}
else{
alert("Sweet lets get some reps in!");
}
for (i=0; i>3; i++){
pushUps(pushUpSets);
}
}
Here, the make a choice button is just dummy to allow us to go to do push ups. Each click decrements our count.
// This is important, we use this event to wait and let the HTML (DOM) load
// before we go ahead and code.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#choice').addEventListener('click', makeChoice);
});
function makeChoice() {
// Call a method to set random pushups and setup the click event
setUpPushUp();
// Here we change the display style of the push up section so that it shows to the player.
document.querySelector('.activity').style.display = 'block';
}
// The pushups variable is declared at the document level
// This way our setUpPushUp and doPushUp functions have easy access.
let pushUps = 0;
function setUpPushUp() {
// Create a random number of pushups, in sets of 10.
// We add an extra 1 so we can call the doPushUp method to initialize.
pushUps = (Math.floor((Math.random() * 10)+1)*10)+1 ;
// Add a click event to the push up button and call our doPushUp method on each click.
document.querySelector('#push').addEventListener('click', doPushUp);
// This is just an init call, it will use the extra 1 we added and place test in our P tag.
doPushUp();
}
function doPushUp() {
// Get a reference to our output element, we will put text to player here.
let result = document.querySelector('p');
// They have clicked, so remove a push up.
pushUps--;
// See if the player has done all the required push ups (i.e. pushUps is 0 or less.)
if (pushUps > 0) {
result.innerText = `You need to crank out ${pushUps} pushUps`;
} else {
result.innerText = 'Nice work!';
}
}
.activity {
display: none;
}
<button id="choice">Make a choice !</button>
<div class="activity">
<p></p>
<button id="push">Push</button>
</div>
I am trying to get a sound file to play faster in order to keep up with the text reveal in the following code. The sound works (in Firefox, anyway), but it only seems to play one instance of the file at a time.
I'd like to have each letter pop onto the screen accompanied by the popping sound. Right now the popping sound is sort of random, and not timed to play with each letter.
I'm wondering if I need to have multiple instances of the sound object, and how to do that.
I already shortened the sound file as much as I could, and the length of the file is shorter than the setTimeout interval I'm using. It just won't overlap multiple copies of the same sound file, for some very good reason that I don't know, I'm sure.
Here is the whole code:
(I tried to JSFiddle it, but couldn't get that to work (I'll save that question for a later date))
<html>
<head>
<style>
#display {
color: white;
font-size: 150%;
padding: 2em 5em;
min-height: 600px;
max-width: 600px;
margin-left: auto;
margin-right: auto;
}
body {
background-color: black;
padding: 0;
margin:0;
}
</style>
<script>
var text = "Test String... 1, 2, 3; Everything seems to be working, but the sound is lagging.";
var charDelay = 40; // Sets the delay time for the character loop
function loadText() {
var i = 0; // Character counter
var myPud = new Audio("http://southernsolutions.us/audio/pud03.ogg");
var displayBox = document.getElementById("display");
displayBox.innerHTML = "<p>";
textLoop();
function textLoop() {
if (i == text.length){ // This condition terminates the loop
displayBox.innerHTML += "</p>";
return;
} else if (i < text.length) { // This condition appends the next character
displayBox.innerHTML += text[i];
i++;
myPud.play();
setTimeout(function(){return textLoop()}, charDelay);
}
}
}
window.onload = function(){loadText()};
</script>
</head>
<body>
<div id="display"></div>
</body>
</html>
I'd suggest that you make the sound loop a little longer, say 1 second. Then, control the sound playing through event listeners so that once the text has finished, you stop the sound playing.
Trying to do it as you're doing it now, you could speed up the sound with how its playing in the audio file. This should give better results. That, or slow down the time out.
Below is some code that I've tested which would let you do it through event listeners. The results are similar to what you had, but if you took your audio file, increased it to 1 second and changed it up to have 24 clicks in there, you'd get the exact effect you were looking for.
Edit: I've also updated the below to take into account the comments.
<script>
var text = "Test String... 1, 2, 3; Everything seems to be working, but the sound is lagging.";
var charDelay = 40; // Sets the delay time for the character loop
function loadText() {
var i = 0; // Character counter
var myPud = new Audio("http://southernsolutions.us/audio/pud03.ogg");
var displayBox = document.getElementById("display");
// Toggle for whether to loop
var stillPlay = true;
displayBox.innerHTML = "<p>";
// Listen for when it ends
myPud.addEventListener("ended", onAudioComplete);
// Begin playing
myPud.play();
// Start the loop
textLoop();
function textLoop() {
if (i == text.length){ // This condition terminates the loop
displayBox.innerHTML += "</p>";
// If we're at the end, we want to stop playing
stillPlay = false;
// Rather than duplicate code, jump straight into the complete function
onAudioComplete(null);
return;
} else if (i < text.length) { // This condition appends the next character
displayBox.innerHTML += text[i];
i++;
// Direct reference to the function to avoid more anony. functions
setTimeout(textLoop, charDelay);
}
}
// On audio complete
function onAudioComplete(e){
// Can we still play? If so, play
if(stillPlay){
myPud.play();
} else {
// Otherwise, remove the event listener, stop and null out.
myPud.removeEventListener("ended", onAudioComplete);
myPud.stop();
myPud = null;
}
}
}
window.onload = loadText;
</script>
In an attempt to overcome Google TTS API's character limit of 100 chars, tried to loop every 100 characters to fetch a fresh mp3 from the api and play seamlessly. Tried multiple ways, but the .play() and the event listeners like canplay/onended doesn't just seem to work inside a loop!
Best that could be achieved is to get all the downloaded tracks to play simultaneously, rather than one after the other. Below is some code :-
if ($("#theinput").attr("value").length > 100){
var len = $("#theinput").attr("value").length;
alert(len);
var audioPlayer = document.getElementById("spokenmemory");
for (var i=0; i < (len / 100); i++) {
var stl=i*100;
var str = $("#theinput").attr("value").substr(stl, 100);
$("#spokenmemory").attr("src", "http://translate.google.com/translate_tts? tl=en&q="+str);
alert(str);
audioPlayer.load();
audioPlayer.addEventListener('canplay', function () {
alert('Loaded');
audioPlayer.play();
} );
//audioPlayer.play();
}
Any help will be appreciated.
Try to use the trigger function instead
fadeInAudio : function(audio){
// audio.play();
audio.trigger("play");
},
fadeOutAudio : function(audio){
// audio.pause();
audio.trigger("pause");
},