Play a random flv from a total of 5 flvs - actionscript-3

I need your help with Actionscipt3.0. To be honest I am reall noob in flash. I am more a 3D Designer so not a lot of flash ;)
Currently I have to create a website where some videos should be played automatically.
When a User opens the URL and lands on the page, a random video of a total of 5 should be played. When the video is finished, it should chose another video of the total of 5 videos.
So an example: It should chose one video of 5 videos. Play it, then it should chose 1 video of 4 videos, then it should chose 1 video of 3 videos..and so on. And after all 5 are played, it should repeat the process.
I hope someone here can help me with that...What i have sofar is this..
var files:Array = [ "Sz01Puppet.flv", "Sz02Puppet.flv",
"Sz03Puppet.flv", "Sz04Puppet.flv", "Sz05Puppet.flv" ]; var
randomFiles:Array = [];
var i:int; for (i=0; i
randomFiles.push(files[Math.floor(Math.random() * files.length)]);
}
trace(randomFiles);
But its not working in any way..
Would be great if someone could help me out

Yup, you're nearly there.
Here's how the for loop should've been written:
var files:Array = [ "Sz01Puppet.flv", "Sz02Puppet.flv", "Sz03Puppet.flv", "Sz04Puppet.flv", "Sz05Puppet.flv" ]; var randomFiles:Array = [];
var i:int;
for(i = 0 ; i < files.length; i++) randomFiles.push(files[Math.floor(Math.random() * files.length)]);
trace(randomFiles);
Still, you're note removing items form the array, so you'll have duplicates.
Here's an an example:
var files:Array = [ "Sz01Puppet.flv", "Sz02Puppet.flv", "Sz03Puppet.flv", "Sz04Puppet.flv", "Sz05Puppet.flv" ];
var shuffledFiles:Array = shuffleArray(files);
//quick test
var testTimer:Timer = new Timer(1000);
testTimer.addEventListener(TimerEvent.TIMER,updateFile);
testTimer.start();
function updateFile(event:TimerEvent):void{
if(shuffledFiles.length == 0) shuffledFiles = shuffleArray(files);//all files played, repeat process
trace('play file',shuffledFiles[0]);
shuffledFiles.shift();
}
function shuffleArray(source:Array,clone:Boolean = true):Array {
var output:Array = [];
var input:Array = clone ? [].concat(source) : source;//clone ? preserve orignal items by making a copy for shuffling, or not
while(input.length) output.push(input.splice(int(Math.random() * input.length-1),1)[0]);
return output;
}
Goodluck

You could use the Array.sort() function to sort it randomly.
// random sort function
function shuffle(a:*, b:*):int
{
return int(Math.random() * 2) - 1;
}
var files:Array = ["Sz01Puppet.flv", "Sz02Puppet.flv", "Sz03Puppet.flv", "Sz04Puppet.flv", "Sz05Puppet.flv"];
var randomFiles:Array = files.sort(shuffle); // get a new instance of the array which is sorted
trace(randomFiles);

Here is one way to do it.

Related

Is there a way to detect audio frequency in HTML 5 web audio API?

I would like to know is there a way we can detect audio frequency from microphone in html 5 web audio. I wish to make an online guitar tuner, and I need to have the audio frequency in hertz, from the sound input. I've seen some EQ and filters effects, but I didn't see anything about frequency recognition.
EDIT:
I found this: http://www.smartjava.org/content/exploring-html5-web-audio-visualizing-sound
The 2nd point (analyser node) is really interesting. I seen his source code, but I can't figure how to connect the analyser to the microphone input.
He calls a playSound() function when the mp3 file starts to play, and there he draws his canvas. But I do not have a playSound() like function...
I wrote a web audio library which, among other things, can detect frequency from mic input. Check it out at https://github.com/rserota/wad#pitch-detection
var voice = new Wad({source : 'mic' });
var tuner = new Wad.Poly();
tuner.add(voice);
voice.play();
tuner.updatePitch() // The tuner is now calculating the pitch and note name of its input 60 times per second. These values are stored in tuner.pitch and tuner.noteName.
var logPitch = function(){
console.log(tuner.pitch, tuner.noteName)
requestAnimationFrame(logPitch)
};
logPitch();
// If you sing into your microphone, your pitch will be logged to the console in real time.
tuner.stopUpdatingPitch(); // Stop calculating the pitch if you don't need to know it anymore.
You should be able to use BiquadFilterNode.
Example code from the link:
var audioCtx = new AudioContext();
var biquadFilter = audioCtx.createBiquadFilter();
biquadfilter.getFrequencyResponse(myFrequencyArray,magResponseOutput,phaseResponseOutput);
You can use the following code to get the frequencies from the mic.
navigator.mediaDevices.getUserMedia({audio:true}).then(function(localStream){
var audioContext = new(window.AudioContext || window.webkitAudioContext)();
var input = audioContext.createMediaStreamSource(localStream);
var analyser = audioContext.createAnalyser();
var scriptProcessor = audioContext.createScriptProcessor();
// Some analyser setup
analyser.smoothingTimeConstant = 0;
analyser.fftSize = 64;
input.connect(analyser);
analyser.connect(scriptProcessor);
scriptProcessor.connect(audioContext.destination);
var getAverageVolume = function( array){
var length = array.length;
var values = 0;
var i = 0;
for (; i < length; i++) {
values += array[i];
}
return values / length;
};
var onAudio = function(){
var tempArray = new window.Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(tempArray);
var latestFrequency = (getAverageVolume(tempArray));
//use latestFrequency
};
scriptProcessor.onaudioprocess = onAudio;
})
.catch(function(){
//Handle error
});

AS3 - Go to random 5 frames out of 7

Hello and thank you so much for your time.
I'm trying to build a quiz for my students, where the start button will go to a random frame out of 7. Then on the landing frame, question appears and the answer is selected via radiobutton then submitted via another button which goes to the next random question. This needs to happen 5 times so it will pick 5 questions randomly out of 7 and not repeating any previous question. If anyone can point me to right direction, it'll be much appreciated.
//Start Button - AS3 Frame #8157
startBtn.addEventListener(MouseEvent.CLICK, startQuiz);
function startQuiz(event:MouseEvent):void{
}
//Submit Button with score count - AS3 Frame #8158
var count:Number = 0;
var mygroup1:RadioButtonGroup = new RadioButtonGroup("group1");
q1a1.group = q1a2.group = q1a3.group = q1a4.group = q1a5.group = mygroup1;
b1.addEventListener(MouseEvent.CLICK, quizHandler1)
function quizHandler1(event:MouseEvent):void{
if(mygroup1.selection.label=="B) 12") {
count = count + 20;
scoreresult.text = (count).toString();
var number_array:Array = [8158,8159,8160,8161,8162,8163,8164 ];
var final_array:Array = [];
var count_selected:int = 5;
var i:int;
for(i = 0; i < count_selected; i++)
{
if(number_array.length == 0)
break;
else
final_array.push(number_array.splice(Math.floor(Math.random() * number_array.length), 1)[0]);
}
trace(final_array);
}
}
Since you don't want to repeat the same value, you need to know what values you've used already. There's a bunch of ways you could do this, but probably the most straight forward is to put all your values in an array, then remove a random value until the array is empty. Here's an example:
// create an array with all the frames you want to visit
var frames:Array = [0, 1, 2, 3, 4, 5, 6];
// when you want to pick one randomly, remove it using splice
var frame:int = frames.splice(Math.random() * frames.length, 1)[0];
// when the array is empty, you've visited every frame
if(frames.length == 0)
trace("all done!");
Here's the docs on splice(): http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#splice%28%29

AS3 do 3 random stops, that are never equal to one another

I have 3 movieclips, each one has 7 frames and labels that play different images, I want to stop each one randomly, but never have them equal the same frame. I was thinking array.push once its called, but I dont know how to do that. So I have this so far:
function startGame(event:MouseEvent)
{
addChild(level6_mc);
addChild(inGameNav_mc);
level6_mc.gotoAndPlay(2);
var timer = setTimeout(startAgain, 1000);
startAgain();
}
// level 6
function startAgain()
{
var randomNumber:Number= Math.floor(Math.random()*7);
var door1 = level6_mc.door1_mc;
var door2 = level6_mc.door2_mc;
var door3 = level6_mc.door3_mc;
door1.gotoAndStop(randomNumber);
door2.gotoAndStop(randomNumber);
door3.gotoAndStop(randomNumber);
}
there has to be an easy way for this, I just cant figure it out. I have been looking all over the net for a solution, but every method is just so complicated. Can anyone help me find a simple solution, and if you tell me to use an array can you please give example. Thanks in advance
I would opt for an approach like this:
function startGame(event:MouseEvent){
addChild(level6_mc);
addChild(inGameNav_mc);
level6_mc.gotoAndPlay(2);
var timer= setTimeout(startAgain, 1000);
startAgain();
}
function startAgain(){
var randomFrames:Array = getRandomFrames(3);
var door1 = level6_mc.door1_mc;
var door2 = level6_mc.door2_mc;
var door3 = level6_mc.door3_mc;
door1.gotoAndStop(randomFrames[0]);
door2.gotoAndStop(randomFrames[1]);
door3.gotoAndStop(randomFrames[2]);
}
/*
Given input of 3, the return should be an array of integers randomly
chosen from the array defined by `frames`. An example would be `[5,2,7]`
*/
function getRandomFrames(var $frameCount:Number):Array {
var frames:Array = [1, 2, 3, 4, 5, 6, 7]
var randomFrames:Array = new Array(Math.min($frameCount, frames.length));
var pos:Number = 0;
for (var i:int = 0; i < randomFrames.length; i++)
{
pos = int(Math.random() * frames.length);
randomFrames[i] = frames.splice(pos, 1)[0];
}
return randomFrames
}
I don't have Flash on this machine, so I can't test. But the idea is that you have an array of frame numbers, 1-7 and you randomly choose 3 of those numbers to be your stop frames.
Since its a small frame count, you can splice the frames out of an array:
function startGame(event:MouseEvent){
addChild(level6_mc);
addChild(inGameNav_mc);
level6_mc.gotoAndPlay(2);
var timer= setTimeout(startAgain, 1000);
startAgain();
}
//level 6
function startAgain(){
var door1 = level6_mc.door1_mc;
var door2 = level6_mc.door2_mc;
var door3 = level6_mc.door3_mc;
var stopsAt:Array = [1,2,3,4,5,6];
door1.gotoAndStop(stopsAt.splice(Math.random()*stopsAt.length, 1)[0]);
door2.gotoAndStop(stopsAt.splice(Math.random()*stopsAt.length, 1)[0]);
door3.gotoAndStop(stopsAt.splice(Math.random()*stopsAt.length, 1)[0]);
var prevNum:int = 0;
function startGame(event:MouseEvent)
{
addChild(level6_mc);
addChild(inGameNav_mc);
level6_mc.gotoAndPlay(2);
var timer = setTimeout(startAgain, 1000);
startAgain();
}
// level 6
function startAgain()
{
var randomNumber:int= getRandomNumber(7,prevNum);
prevNum = randomNumber;
var door1 = level6_mc.door1_mc;
var door2 = level6_mc.door2_mc;
var door3 = level6_mc.door3_mc;
door1.gotoAndStop(randomNumber);
door2.gotoAndStop(randomNumber);
door3.gotoAndStop(randomNumber);
}
function getRandomNumber(length:int,previousNumber:int):int
{
var currentNumber:int;
do{
currentNumber = Math.floor(1+Math.random()*length);
}while(currentNumber==previousNumber);
return currentNumber;
}

randomize buttons on in as3 from array

I'm pretty novice to flash 5.5, im trying to build a quiz for my elementary students.
So far I have made the layout, created the image buttons, and I used to as3 to advance the quiz.
So what I'm, looking for is the ability to shuffle the image buttons/answers. Here is a sample of what i have so far.
the red ______
apple (button of apple) boy (button of boy) pineapple (button with pineapple)
In my example, the pictures are buttons, the correct answer is apple. I have tried to create an array, after hours of google searches. This is my code, I'm doing something wrong but I have no idea what. Please help.
Please help.
function Main() {
var button:Array = [];
button.push("choice1");
button.push("choice2");
button.push("choice3");
ShuffleArray(button);
trace(button);
}
function ShuffleArray(button:Array)
{
for (var i:int = button.length-1; i >=0; i--)
{
var randomIndex:int = Math.floor(Math.random()*(i+1));
var itemAtIndex:Object = button[randomIndex];
button[randomIndex] = button[i];
button[i] = itemAtIndex;
thanks in advance.
thanks in advance.
Try something more like this:
protected var button:Array=[choice1, choice2, choice3];//note no quotes, puts in the actual objects
function Main() {
super();
randomArray=shuffleArray(button);
var prevX:int = 0;
var space:int = 10;
//places the buttons from left to right in the order
//they were in the random array
//uses existing y
for (var i:int=0; i<randomArray.length; i++) {
var btn:DisplayObject = randomArray[i] as DisplayObject;
btn.x = prevX;
prevX = btn.x + btn.width + space;
}
}
protected function shuffleArray(inArray:Array):Array {
//create copy of array so as not to alter it
var tempArray = new Array().concat(inArray);
//resultarray (we'll be destroying the temp array)
var resultArray:Array = [];
while(tempArray.length>0) {
var index:int = int(Math.random() * tempArray.length);
//delete object from random location and put it into result array
resultArray.push(tempArray.splice(index, 1)[0]);
}
return resultArray;
}
Note this assumes you're using a document Class and that your buttons are already on the stage at the same y position.

FLVPlayback component and Actionscript. Random Flv playback with Arrays.

I have come a little closer with my project, and still need some help please. I have 5 Flvs which i want to play randomly on this page www.music-puppets.com/
The .fla file I have created contains this code:
var files:Array = [ "Sz01Puppet.flv", "Sz02Puppet.flv", "Sz03Puppet.flv", "Sz04Puppet.flv", "Sz05Puppet.flv" ];
var shuffledFiles:Array = shuffleArray(files);
//quick test
var testTimer:Timer = new Timer(1000);
testTimer.addEventListener(TimerEvent.TIMER,updateFile);
testTimer.start();
function updateFile(event:TimerEvent):void{
if(shuffledFiles.length == 0) shuffledFiles = shuffleArray(files); //all files played, repeat process
trace('play file',shuffledFiles[0]);
shuffledFiles.shift();
}
function shuffleArray(source:Array,clone:Boolean = true):Array {
var output:Array = [];
var input:Array = clone ? [].concat(source) : source; //clone ? preserve orignal items by making a copy for shuffling, or not
while(input.length) output.push(input.splice(int(Math.random() * input.length-1),1) [0]);
return output;
}
This script works. In the Output every flv is listed randomly, and then repeated. Next up i want this AS Script to work with an FLV Component.
But how to I get that to work?
In my library I have the 5 flvs, and flvplayback component.
I dragged the FLVPlayback component to the stage, but I can only add one flv in the source. How do I get my working actionscript to work with the FLVPlayback component.
Here you can see how my screen looks like.
capture01.jpg
capture02.jpg
Would be great to get some feedback :)
First of all you need to give your FLVPlayback component an instance name using the properties panel. That will let you talk to it from the code.
Next you will need to add a listener to the FLVPlayback component to detect when each video finishes. Let's assume you've given it an instance name of myVideo:
myVideo.addEventListener(VideoEvent.COMPLETE,onVideoComplete);
You will need a handler function for this, and that will look similar to the function you currently use for each iteration of your timer:
function onVideoComplete(event:VideoEvent):void {
if(shuffledFiles.length == 0) shuffledFiles = shuffleArray(files); //all files played, repeat process
myVideo.source = shuffledFiles.shift(); //grab the first array item to play in the FLVPlayback component
}
Finally, make sure that your FLVPlayback component is set to play a new source automatically, then assign the first video to get things going:
myVideo.autoPlay = true;
myVideo.source = shuffledFiles.shift();
If anyone is interested. I have got the running code :)
import flash.events.Event;
import fl.video.*;
var files:Array;
var shuffledFiles:Array;
loaderInfo.addEventListener(Event.COMPLETE,ready);
function ready(event:Event):void{
loaderInfo.removeEventListener(Event.COMPLETE,ready);
//swf rescale setup
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE,stageResized);
//get FlashVars - a string converted into an Array by spliting it on the , character
//if the files FlashVar is setup correctly use the data, else use default values
if(loaderInfo.parameters.files != undefined) files = loaderInfo.parameters.files.indexOf(',') > 0 ? loaderInfo.parameters.files.split(",") : [loaderInfo.parameters.files];
else files = [ "Sz01Puppet.flv", "Sz02Puppet.flv", "Sz03Puppet.flv", "Sz04Puppet.flv", "Sz05Puppet.flv" ];
shuffledFiles = shuffleArray(files);
//play the 1st video
videoPlayer.source = shuffledFiles[0];
shuffledFiles.shift();
//see when the video finished playing
videoPlayer.addEventListener(VideoEvent.COMPLETE,videoFinished);
}
function videoFinished(event:VideoEvent):void{
if(shuffledFiles.length == 0) shuffledFiles = shuffleArray(files);//all files played, repeat process
videoPlayer.source = shuffledFiles[0];//play the first video in the random list
videoPlayer.play();
trace('playing',shuffledFiles[0]);
shuffledFiles.shift();//remove the first video from the random list (e.g. [2,0,1].shift() becomes [0,1])
}
function stageResized(event:Event):void{
videoPlayer.width = stage.stageWidth;
videoPlayer.height = stage.stageHeight;
}
function shuffleArray(source:Array,clone:Boolean = true):Array {
var output:Array = [];
var input:Array = clone ? [].concat(source) : source;//clone ? preserve orignal items by making a copy for shuffling, or not
while(input.length) output.push(input.splice(int(Math.random() * input.length-1),1)[0]);
return output;
}