I have this working in Javascript but can't seem to get it working on Titanium.
Here is the code:
var index = 0;
var i = 0;
// Filename
var wordSoundArray = [];
wordSoundArray.push('audio/the.mp3');
wordSoundArray.push('audio/of.mp3');
wordSoundArray.push('audio/and.mp3');
wordSoundArray.push('audio/a.mp3');
wordSoundArray.push('audio/to.mp3');
wordSoundArray.push('audio/in.mp3');
wordSoundArray.push('audio/is.mp3');
wordSoundArray.push('audio/you.mp3');
wordSoundArray.push('audio/that.mp3');
wordSoundArray.push('audio/it.mp3');
wordSoundArray.push('audio/he.mp3');
wordSoundArray.push('audio/was.mp3');
wordSoundArray.push('audio/for.mp3');
wordSoundArray.push('audio/on.mp3');
wordSoundArray.push('audio/are.mp3');
newWordBtn.addEventListener("click", function(e){
wordLabel.text = newWordArray[i++];
if (i === newWordArray.length)
i = 0;
var snd = Titanium.Media.createSound({url:wordSoundArray[index++]});
if (index === wordSoundArray.length)
index = 0;
if (snd.isPlaying()) {
snd.stop();
snd.play();
} else {
snd.play();
}
});
When a user presses the button they get a new word and the sound that goes with that word. However, if the user presses the button before the sound is finished it simply starts the new sound and they overlap each other. That is where the snd.isPlaying portion of the code of the code comes in. I'm pretty sure my mistake is in there.
So you actually have dead code here:
var snd = Titanium.Media.createSound({url:wordSoundArray[index++]}));
...
// You just created the sound, so it will never be playing right off the bat
if (snd.isPlaying()) {
// This will never be called
snd.stop();
snd.play();
} else {
// This will happen every time the user clicks the button
snd.play();
}
I think its good practice to pre-load all your sound assets before you start execution, so maybe try replacing your wordSoundArray with entries of the form:
wordSoundArray.push(Titanium.Media.createSound({url:'audio/the.mp3'});
Once you have done this (all our sound assets are preloaded, this will be good for memory too) we can change the listener to something like this:
newWordBtn.addEventListener("click", function(e){
wordLabel.text = newWordArray[i++];
if (i === newWordArray.length)
i = 0;
// Instead of creating the sound, just fetch it!
var snd = wordSoundArray[index++];
if (index === wordSoundArray.length)
index = 0;
// Now this will work, but maybe you want to make sure all the sounds are off instead?
if (snd.isPlaying()) {
snd.stop();
snd.play();
} else {
snd.play();
}
});
Looking at your code though, it appears you want to stop the previous sound playing and then start the next one, so you would need to change the listener to this:
newWordBtn.addEventListener("click", function(e){
wordLabel.text = newWordArray[i++];
if (i === newWordArray.length)
i = 0;
// Stop the last sound from playing
if(index > 0) {
var lastSound = wordSoundArray[index-1];
lastSound.stop();
}
// Instead of creating the sound, just fetch it!
var nextSound = wordSoundArray[index++];
if (index === wordSoundArray.length)
index = 0;
// Play the next sound
nextSound.play();
});
Related
I want to be able to change the value of a global variable when it is being used by a function as a parameter.
My javascript:
function playAudio(audioFile, canPlay) {
if (canPlay < 2 && audioFile.paused) {
canPlay = canPlay + 1;
audioFile.play();
} else {
if (canPlay >= 2) {
alert("This audio has already been played twice.");
} else {
alert("Please wait for the audio to finish playing.");
};
};
};
const btnPitch01 = document.getElementById("btnPitch01");
const audioFilePitch01 = new Audio("../aud/Pitch01.wav");
var canPlayPitch01 = 0;
btnPitch01.addEventListener("click", function() {
playAudio(audioFilePitch01, canPlayPitch01);
});
My HTML:
<body>
<button id="btnPitch01">Play Pitch01</button>
<button id="btnPitch02">Play Pitch02</button>
<script src="js/js-master.js"></script>
</body>
My scenario:
I'm building a Musical Aptitude Test for personal use that won't be hosted online. There are going to be hundreds of buttons each corresponding to their own audio files. Each audio file may only be played twice and no more than that. Buttons may not be pressed while their corresponding audio files are already playing.
All of that was working completely fine, until I optimised the function to use parameters. I know this would be good to avoid copy-pasting the same function hundreds of times, but it has broken the solution I used to prevent the audio from being played more than once. The "canPlayPitch01" variable, when it is being used as a parameter, no longer gets incremented, and therefore makes the [if (canPlay < 2)] useless.
How would I go about solving this? Even if it is bad coding practise, I would prefer to keep using the method I'm currently using, because I think it is a very logical one.
I'm a beginner and know very little, so please forgive any mistakes or poor coding practises. I welcome corrections and tips.
Thank you very much!
It's not possible, since variables are passed by value, not by reference. You should return the new value, and the caller should assign it to the variable.
function playAudio(audioFile, canPlay) {
if (canPlay < 2 && audioFile.paused) {
canPlay = canPlay + 1;
audioFile.play();
} else {
if (canPlay >= 2) {
alert("This audio has already been played twice.");
} else {
alert("Please wait for the audio to finish playing.");
};
};
return canPlay;
};
const btnPitch01 = document.getElementById("btnPitch01");
const audioFilePitch01 = new Audio("../aud/Pitch01.wav");
var canPlayPitch01 = 0;
btnPitch01.addEventListener("click", function() {
canPlayPitch01 = playAudio(audioFilePitch01, canPlayPitch01);
});
A little improvement of the data will fix the stated problem and probably have quite a few side benefits elsewhere in the code.
Your data looks like this:
const btnPitch01 = document.getElementById("btnPitch01");
const audioFilePitch01 = new Audio("../aud/Pitch01.wav");
var canPlayPitch01 = 0;
// and, judging by the naming used, there's probably more like this:
const btnPitch02 = document.getElementById("btnPitch02");
const audioFilePitch02 = new Audio("../aud/Pitch02.wav");
var canPlayPitch02 = 0;
// and so on
Now consider that global data looking like this:
const model = {
btnPitch01: {
canPlay: 0,
el: document.getElementById("btnPitch01"),
audioFile: new Audio("../aud/Pitch01.wav")
},
btnPitch02: { /* and so on */ }
}
Your event listener(s) can say:
btnPitch01.addEventListener("click", function(event) {
// notice how (if this is all that's done here) we can shrink this even further later
playAudio(event);
});
And your playAudio function can have a side-effect on the data:
function playAudio(event) {
// here's how we get from the button to the model item
const item = model[event.target.id];
if (item.canPlay < 2 && item.audioFile.paused) {
item.canPlay++;
item.audioFile.play();
} else {
if (item.canPlay >= 2) {
alert("This audio has already been played twice.");
} else {
alert("Please wait for the audio to finish playing.");
};
};
};
Side note: the model can probably be built in code...
// you can automate this even more using String padStart() on 1,2,3...
const baseIds = [ '01', '02', ... ];
const model = Object.fromEntries(
baseIds.map(baseId => {
const id = `btnPitch${baseId}`;
const value = {
canPlay: 0,
el: document.getElementById(id),
audioFile: new Audio(`../aud/Pitch${baseId}.wav`)
}
return [id, value];
})
);
// you can build the event listeners in a loop, too
// (or in the loop above)
Object.values(model).forEach(value => {
value.el.addEventListener("click", playAudio)
})
below is an example of the function.
btnPitch01.addEventListener("click", function() {
if ( this.dataset.numberOfPlays >= this.dataset.allowedNumberOfPlays ) return;
playAudio(audioFilePitch01, canPlayPitch01);
this.dataset.numberOfPlays++;
});
you would want to select all of your buttons and assign this to them after your html is loaded.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
const listOfButtons = document.getElementsByClassName('pitchButton');
listOfButtons.forEach( item => {
item.addEventListener("click", () => {
if ( this.dataset.numberOfPlays >= this.dataset.allowedNumberOfPlays ) return;
playAudio("audioFilePitch" + this.id);
this.dataset.numberOfPlays++;
});
I am trying to play music in my web browser under a certain condition, threshold = true for 10 iteration and here is my code:
<script>
var threshold = true;
for (var i=0 ; i<10; i++){// number of iteration
if ( threshold){
var audio = new Audio('song.mp3');
audio.play();
}
}
</script>
while I don't get any error the song won't be played in my browser; therefore I don't know what can possibly be wrong.
Firstly, you can't generally call audio.play() unless you're doing it in immediate response to some sort of user action. This is due to the autoplay policy.
Next, I would leave the looping up to the browser:
audio.loop = true;
Now, use the seeked event to figured out when the audio went back in time. (Most likely, it looped.) When this happens, increment a loop count. Then, see if we've looped too many times and pause if so.
let maxLoops = 10;
let lastTime = 0;
let loops = 0;
audio.addEventListener('seeked', (e) => {
if (e.target.currentTime < lastTime) {
loops++;
}
if (loops >= maxLoops) {
e.target.pause();
}
lastTime = e.target.currentTime;
});
I seem to have a very strange problem. I am trying to play a video which is being streamed live using a web browser. For this, I am looking at the MediaSource object. I have got it in a way so that the video is taken from a server in chunks to be played. The problem is that the first chunk plays correctly then playback stops.
To make this even more strange, if I put the computer to sleep after starting streaming, then wake it up andthe video will play as expected.
Some Notes:
I am currently using chrome.
I have tried both of them ,with and without calling MediaSource's endOfStream.
var VF = 'video/webm; codecs="vp8,opus"';
var FC = 0;
alert(MediaSource.isTypeSupported(VF));
var url = window.URL || window.webkitURL;
var VSRC = new MediaSource();
var VURL = URL.createObjectURL(VSRC);
var bgi, idx = 1;
var str, rec, dat = [], datb, brl;
var sbx;
//connect the mediasource to the <video> elment first.
vid2.src = VURL;
VSRC.addEventListener("sourceopen", function () {
// alert(VSRC.readyState);
//Setup the source only once.
if (VSRC.sourceBuffers.length == 0) {
var sb = VSRC.addSourceBuffer(VF);
sb.mode = 'sequence';
sb.addEventListener("updateend", function () {
VSRC.endOfStream();
});
sbx = sb;
}
});
//This function will be called each time we get more chunks from the stream.
dataavailable = function (e) {
//video is appended to the sourcebuffer, but does not play in video element
//Unless the computer is put to sleep then awaken!?
sbx.appendBuffer(e.result);
FC += 1;
//These checks behave as expected.
len.innerHTML = "" + sbx.buffered.length + "|" + VSRC.duration;
CTS.innerHTML = FC;
};
You are making two big mistakes:
You can only call sbx.appendBuffer when sbx.updating property is false, otherwise appendBuffer will fail. So what you need to do in reality is have a queue of chunks, and add a chunk to the queue if sbx.updating is true:
if (sbx.updating || segmentsQueue.length > 0)
segmentsQueue.push(e.result);
else
sbx.appendBuffer(e.result);
Your code explicitly says to stop playing after the very first chunk:
sb.addEventListener("updateend", function () {
VSRC.endOfStream();
});
Here is what you really need to do:
sb.addEventListener("updateend", function () {
if (!sbx.updating && segmentsQueue.length > 0) {
sbx.appendBuffer(segmentsQueue.shift());
}
});
I have the following function, that is called once in my program. When there is no user interaction it starts over again and again by recursion when the array is printed out. But when a user clicks on a link the function shall be stopped first (no more output from the array) and then be started again with new parameters.
function getText(mode){
var para = mode;
var url = "getText.php?mode=" + para;
var arr = new Array();
//get array via ajax-request
var $div = $('#text_wrapper');
$.each(arr, function(index, value){
eachID = setTimeout(function(){
$div.html(value).stop(true, true).fadeIn().delay(5000).fadeOut();
if(index == (arr.length-1)){
clearTimeout(eachID);
getText(para);
}
}, 6000 * index);
});
}
My code doesn't really stop the function but calling it once more. And that eventuates in multiple outputs and overlaying each other. How can I ensure that the function stops and runs just one at a time?
$(document).ready(function() {
$("#div1, #div2").click(function(e){
e.preventDefault();
var select = $(this).attr("id");
clearTimeout(eachID);
getText(select);
});
});
You keep overwriting eachID with the latest setTimeout, so when you clearTimeout(eachID) you are only stopping the last one.
Personally, I like to do things like this:
id = 0;
timer = setInterval(function() {
// do stuff with arr[id]
id++;
if( id >= arr.length) clearInterval(timer);
},6000);
This way, you only have one timer running, and you can clear it at any time.
I was trying to show a text gradually on the screen (like marquee). e.g. H.. He.. Hell.. Hello. when I'm tracing it in debug in VS2010 it's working! but when it's actually running it shows the whole sentence at once.
I made a certain "delay" for about 3 seconds between each letter so it would suppose to take a while, but in reality it's shows everything immediately.
Who's the genius to solve this mystery? (please don't give me advices how to create the marquee effect, it's not the issue anymore. now it's just a WAR between me and javascript!) I'm assuming that it has to do with synchronization when calling function from function?
Thanks to whomever will help me get my sanity back.
you can download the code from here (VS project):
http://pcgroup.co.il/downloads/misc/function_from_function.zip
or view it here:
<body>
<script type="text/javascript">
//trying to display this source sentence letter by letter:
var source = "hi javascript why are you being such a pain";
var target = "";
var pos = 0;
var mayGoOn = false;
//this function calls another function which suppose to "build" the sentence increasing index using the global var pos (it's even working when following it in debug)
function textticker() {
if (pos < source.length) {
flash();
if (mayGoOn == true) {
pos++;
mayGoOn = false;
document.write(target);
textticker();
}
}
}
function flash() {
//I tried to put returns everywhere assuming that this may solve it probably one of them in not necessary but it doesn't solve it
if (mayGoOn == true) { return; }
while (true) {
var d = new Date();
if (d.getSeconds() % 3 == 0) {
//alert('this suppose to happen only in about every 3 seconds');
target = source.substring(0, pos);
mayGoOn = true;
return;
}
}
}
textticker();
</script>
You're obviously doing it wrong. Take a look at this.
var message = "Hello World!";
function print(msg, idx) {
if(!idx) {
idx = 0;
}
$('#hello').html(msg.substring(0, idx));
if(idx < msg.length) {
setTimeout(function() { print(msg, idx + 1) }, 200);
}
}
print(message);
Demo: http://jsbin.com/evehus