CROSSFADE SOUND AS 3.0 - actionscript-3

I'm an AS 3.0 project where I'm getting into an array sounds to compose a particular set of phrases. The problem is that it sounds too much shock and wanted to make a crossfade effect to better attach a word to each other.
My problem is that I can not join them because every sound played one after another, is there any way to merge that can reach the end of a sound with the beginning of the next?
Thank you very much.
The code I'm working with is something like this:
for (iii = 0; iii < numpalabras; iii ++)
{
if (abuscar2 = abuscarArray[iii])
{
vocaliza(abuscar2, iii);
}
}
iii = 0;
localSound = lossonidosArray[iii];
var soundTrans:SoundTransform = new SoundTransform;
soundTrans=SoundMixer.soundTransform;
soundTrans.volume=1;
soundTrans.pan=0;
elcanal.soundTransform = soundTrans;
elcanal = localSound.play(85, 0, soundTrans);
elcanal.addEventListener(Event.SOUND_COMPLETE, locutapalabra);
}
function locutapalabra(event:Event)
{
if (iii < (ii))
{
iii=iii+1;
localSound = lossonidosArray[iii];
var soundTrans:SoundTransform = new SoundTransform;
soundTrans=SoundMixer.soundTransform;
soundTrans.volume=1;
soundTrans.pan=0;
elcanal.soundTransform = soundTrans;
elcanal = localSound.play(85, 0, soundTrans);
elcanal.addEventListener(Event.SOUND_COMPLETE, locutapalabra);
}
function vocaliza(abuscar2, iii)
{
if (datosXML.palabras.(palabra == abuscar2).palabra == abuscar2)
{
ii++;
elfic = "mp3/" + datosXML.palabras.(palabra == abuscar2).fichero;
var elsonido :Sound = new Sound();
elsonido.addEventListener(IOErrorEvent.IO_ERROR, errorprogreso);
var laurl:URLRequest = new URLRequest(elfic);
elsonido.load(laurl);
lossonidosArray[ii] = elsonido;
}
}
I am new to AS 3.0 programming and I do not get clear my code to make the words come together with each other, because I get to build such phrases of several words.
Thank you very much.

For cross-fading, you can use a tween library (like greensock) to tween the volume of the sound channel:
var sound:Sound = new Sound(...);
// start volume at 0
var soundChannel = sound.play(0, 0, new SoundTransform(0));
// tween volume to 1
TweenMax.to(soundChannel, 1, { volume: 1 } );
// half a second before the sound is complete, tween volume to 0
TweenMax.to(soundChannel, .5, {volume: 0, delay:(sound.length/1000)-.5});

var timer:Timer = new Timer(3000) //set to how long to wait
timer.addEventListener(TimerEvent.TIMER, nextSound);
function nextSound(e:Event):void
{
listenForNextSound(); //this is where you play your next sound
}
timer is a timer variable, and when 3 seconds pass (or however long you want) the next sound will start playing.
To make your timer variable a bit more accurate, you can make it the duration of the sound by listening for the COMPLETE Event:
yourTimer.addEventListener(Event.COMPLETE, function() {
timer.delay = yourTimer.length - howMuchTimeBefore;
});

Related

Cocos2d-js: effect on cocos2d-js application running on browser while a move from one application to another application

i was running parkour game given on cocos2d website on my browser. everything was working fine, but when i move from my browser to sublime text and returned to my browser, the running player start to show some unexpected behaviour, the player disappeared from its position and and after few second it fall on the ground and then start running again .whenever i move from one application to another it happens.
i don't why its happening. could some one tell me how to prevent this from happen?
here is the code for animation layer:-
var AnimationLayer = cc.Layer.extend({
spriteSheet: null,
runningAction: null,
sprite: null,
space:null,
body:null,
shape:null,
ctor:function (space) {
this._super();
this.space = space;
this.init();
this._debugNode = cc.PhysicsDebugNode.create(this.space);
this._debugNode.setVisible(false);
// Parallax ratio and offset
this.addChild(this._debugNode, 10);
},
init:function () {
this._super();
// create sprite sheet
cc.spriteFrameCache.addSpriteFrames(res.runner_plist);
this.spriteSheet = cc.SpriteBatchNode.create(res.runner_png);
this.addChild(this.spriteSheet);
// init runningAction
var animFrames = [];
for (var i = 0; i < 8; i++) {
var str = "runner" + i + ".png";
var frame = cc.spriteFrameCache.getSpriteFrame(str);
animFrames.push(frame);
}
var animation = cc.Animation.create(animFrames, 0.1);
this.runningAction = cc.RepeatForever.create(cc.Animate.create(animation));
//create runner through physic engine
this.sprite = cc.PhysicsSprite.create("#runner0.png");
var contentSize = this.sprite.getContentSize();
// init body
this.body = new cp.Body(1, cp.momentForBox(1, contentSize.width, contentSize.height));
this.body.p = cc.p(g_runnerStartX, g_groundHight + contentSize.height / 2);
this.body.applyImpulse(cp.v(150, 0), cp.v(0, 0));//run speed
this.space.addBody(this.body);
//init shape
this.shape = new cp.BoxShape(this.body, contentSize.width - 14, contentSize.height);
this.space.addShape(this.shape);
this.sprite.setBody(this.body);
this.sprite.runAction(this.runningAction);
this.spriteSheet.addChild(this.sprite);
this.scheduleUpdate();
},
getEyeX:function () {
return this.sprite.getPositionX() - g_runnerStartX;
}});
and this is the code for playScene.js:-
var PlayScene = cc.Scene.extend({
space:null,
gameLayer:null,
// init space of chipmunk
initPhysics:function() {
this.space = new cp.Space();
// Gravity
this.space.gravity = cp.v(0, -350);
// set up Walls
var wallBottom = new cp.SegmentShape(this.space.staticBody,
cp.v(0, g_groundHight),// start point
cp.v(4294967295, g_groundHight),// MAX INT:4294967295
0);// thickness of wall
this.space.addStaticShape(wallBottom);
},
onEnter:function () {
this._super();
this.initPhysics();
this.gameLayer = cc.Layer.create();
//add three layer in the right order
this.gameLayer.addChild(new BackgroundLayer(), 0, TagOfLayer.background);
this.gameLayer.addChild(new AnimationLayer(this.space), 0, TagOfLayer.Animation);
this.addChild(this.gameLayer);
this.addChild(new StatusLayer(), 0, TagOfLayer.Status);
this.scheduleUpdate();
},
update:function (dt) {
// chipmunk step
this.space.step(dt);
var animationLayer = this.gameLayer.getChildByTag(TagOfLayer.Animation);
var eyeX = animationLayer.getEyeX();
this.gameLayer.setPosition(cc.p(-eyeX,0));
}
});
Ok, this may or may not solve the issue some scenarios, but after looking at it profoundly, the biggest suspect seems to be a lack of steps in the calculations of Chipmunk when the framerate drops (which appears to happen when you resize or minimize/maximize the screen).
The closest thing to a fix that I've found comes from a lead in this post in the forums, and which I've adapted it like this: where you have this.space.step(dt); in your update function, change it for the following:
var timeWindow = 1/60; //replace by your configured FPS rate if it's not 60
var steps = Math.ceil(dt / timeWindow);
var i = 0;
for (; i < steps; i++) {
this.space.step(timeWindow);
}
This should ensure that even if your application drops below 60fps the physics simulation will be updated properly, and this problem should not happen anymore.

Toggle Mute sound in Actionscript 3

I have several tracks of audio that are in sinc. I would like to have one "TitleMusic" ON from the start, And allow the user to toggle ON and off the other tracks. My code As it stands has the "TitleMusic" playing from the start with all the other tracks playing too. I need to switch "track8" and all the other tracks (not showing) around so they are off at the start.This took me a long time to get to this point, I just need some help turning it around. Thanks
import flash.media.Sound;
import flash.media.SoundChannel;
var soundOn:Boolean = true;//This music is ON when we start
var myMusic:TitleMusic = new TitleMusic();
var myChannel1:SoundChannel = myMusic.play(0,1000);//endless loop, in effect
var soundOn3:Boolean = true; //music is ON when we start
var myMusic3:track8 = new track8();
var myChannel3:SoundChannel = myMusic3.play(0,1000); // endless loop, in effect
var myTransform3:SoundTransform;
mySoundButton3.addEventListener(MouseEvent.CLICK,toggleSound3);
mySoundButton3.buttonMode = true;
mySoundButton3.mouseChildren = false;
function toggleSound3(e:MouseEvent)
{
if(soundOn3)
{
// turn sound off
myTransform3 = new SoundTransform();
myTransform3.volume = 0; // silent
myChannel3.soundTransform = myTransform3;
soundOn3 = false;
mySoundButton3.myButtonText.text = "click to turn sound ON";
}
else // sound is off
{
// turn sound on
myTransform3 = new SoundTransform();
myTransform3.volume = 1; // full volume
myChannel3.soundTransform = myTransform3;
soundOn3 = true;
mySoundButton3.myButtonText.text = "click to turn sound OFF";
}
}
Couldn't you just put this line right after mySoundButton3.mouseChildren = false;:
toggleSound3(null);
Or, to be more efficient with memory, you could do this:
Take this line:
var myChannel3:SoundChannel = myMusic3.play(0,1000);
and change it to:
var myChannel3:SoundChannel;
This makes it so you're not actually starting the sound right away, but just creating the pointer for it (var)
Then, in your turn on block right after // turn sound on:
if(!myChannel13){
myChannel3 = myMusic3.play(0,1000);
}
This checks to see if you've started the sound yet, if not, it creates/starts the sound
You'll also want to change this line in your sound off block:
myChannel3.soundTransform = myTransform3;
to this
if(myChannel13){
myChannel3.soundTransform = myTransform3;
}
That way, if the off button is clicked before the on button, it won't throw an error.

Record Paper.js path object and redraw again later

I draw with a mouse Paper.js. I need to keep these strokes and replay them at the same rate as in the video replay. How can I accomplish this?
In paper.js, the onFrame() function is called up to 60 times per second, while the onMouseMove() function "is called when the mouse moves within the project view", and contains the position of the mouse. By using both functions you can store the mouse motions and replay them later with close to the same time between positions.
var mousePosition = null;
function onMouseMove(event) {
if (mousePosition != null) {
var path = new Path();
path.strokeColor = 'black';
path.moveTo(mousePosition);
path.lineTo(event.point);
}
mousePosition = event.point;
}
var recordedPositions = [];
var delayFrames = 60;
function onFrame(event) {
if (mousePosition != null) {
recordedPositions.push(mousePosition);
if (recordedPositions.length > delayFrames) {
var path = new Path();
path.strokeColor = 'red';
delayedPositionIndex = recordedPositions.length - delayFrames;
path.moveTo(recordedPositions[delayedPositionIndex - 1]);
path.lineTo(recordedPositions[delayedPositionIndex]);
}
}
}
I do not know the timing accuracy/resolution/dependability of onFrame(). Alternatively you could just use javascript timing events as in this answer: How can I use javascript timing to control on mouse stop and on mouse move events

AS3 play sounds in an array in a sequence

This is being programmed in Flash CS5.5:
I want to push a button, and play through the entire array one sound at a time. When the first sound stops, the second begins, etc. all the way until the last sound plays. When the last sound finishes, all sound should stop, and if you push the play button again, it should start over at the beginning, and play through all sounds again.
Currently, to advance to the next sound, you have to push the button again. I'm thinking the SOUND_COMPLETE needs to be used... I'm just not sure how, hence the empty function. I only want to have to push play one time to hear the entire array in a sequence. Any ideas?
var count;
var songList:Array = new Array("test1.mp3","test2.mp3","test3.mp3");
count = songList.length;
myTI.text = count;
var currentSongId:Number = 0;
playBtn.addEventListener(MouseEvent.CLICK, playSound);
function playSound(e:MouseEvent):void{
if(currentSongId < songList.length)
{
var mySoundURL:URLRequest = new URLRequest(songList[currentSongId]);
var mySound:Sound = new Sound();
mySound.load(mySoundURL);
var mySoundChannel:SoundChannel = new SoundChannel();
mySoundChannel = mySound.play();
currentSongId++;
mySoundChannel.addEventListener(Event.SOUND_COMPLETE,handleSoundComplete)
}
if(currentSongId == songList.length)
{
currentSongId = 0;
}
}
function handleSoundComplete(event:Event){
}
You should use functions to modulate what you do, this will make your code more readable.
private Array songList = new Array("test1.mp3", "test2.mp3");
public function onPlayBtnPressed(){
currentSongIndex = 0;
PlaySongFromIndex(currentSongIndex);
}
public function PlaySongFromIndex(songIndex:int){
//do what ever here to simply play a song.
var song:Sound = new Sound(songList[songIndex]).Play()
//Addevent listener so you know when the song is complete
song.addEventListener(Event.Complete, songFinished);
currentSongIndex++;
}
public function songFinished(e:Event){
//check if all the songs where played, if so resets the song index back to the start.
if(currentSongIndex < listSong.Length){
PlaySongFromIndex(currentSongIndex);
} else {
currentSongIndex=0;
}
}
This wont compile its just to show an exemple, hope this helps.

Multiple movieclips all go to the same spot; What am i doing wrong?

So I'm trying to shoot multiple bullets out of my body and it all works except I have an odd problem of just one bullet showing up and updating to set position for the new ones.
I have a move able player thats supposed to shoot and I test this code by moving the player and shooting. Im taking it step by step in creating this.
The result of tracing the bulletContainer counts correctly in that its telling me that movieclips ARE being added to the stage; I Just know it comes down to some kind of logic that im forgetting.
Here's My Code (The Bullet it self is a class)
UPDATE*
Everything in this code works fine except for I stated earlier some code seems reduntned because I've resorted to a different approaches.
BulletGod Class:
public class bulletGod extends MovieClip{
//Register Variables
//~Global
var globalPath = "http://127.0.0.1/fleshvirusv3/serverside/"
//~MovieCLips
var newBullet:bulletClass = new bulletClass();
//~Boolean
var loadingBulletInProgress:Number = 0;
var shootingWeapon:Number = 0;
//~Timers
var fireBulletsInterval = setInterval(fireBullets, 1);
var bulletFireEvent;
//~Arrays
var bulletArray:Array = new Array();
var bulletType:Array = new Array();
var bulletContainer:Array = new Array();
//~Networking
var netBulletRequest:URLRequest = new URLRequest(globalPath+"bullets.php");
var netBulletVariables:URLVariables = new URLVariables();
var netBulletLoader:URLLoader = new URLLoader();
//~Bullet Image Loader
var mLoader:Loader = new Loader();
var mRequest:URLRequest = new URLRequest();
public function bulletGod() {
//Load every bullet for every gun
//Compile data to be requested
netBulletVariables.act = "loadBullets"
netBulletRequest.method = URLRequestMethod.POST
netBulletRequest.data = netBulletVariables;
netBulletLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
netBulletLoader.addEventListener(Event.COMPLETE, getBulletImages);
netBulletLoader.load(netBulletRequest);
}
private function getBulletImages(bulletImageData:Event){
//Request every bullet URL image
//Set vars
var bulletData = bulletImageData.target.data;
//Load images
for(var i:Number = 0; i < bulletData.numBullets; i++){
bulletArray.push(bulletData["id"+i.toString()]);
bulletType.push(bulletData["bullet"+i.toString()]);
//trace(bulletData["id"+i]+"-"+bulletData["bullet"+i]);
}
//All the arrays have been set start firing the image loader/replacer
var imageLoaderInterval = setInterval(imageReplacer, 10);
}
private function imageReplacer(){
//Check to see which image needs replacing
if(!loadingBulletInProgress){
//Begin loading the next image
//Search for the next "String" in the bulletType:Array, and replace it with an image
for(var i:Number = 0; i < bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//Load this image
mRequest = new URLRequest(globalPath+"ammo/"+bulletType[i]);
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadImage);
mLoader.load(mRequest);
//Stop imageReplacer() while we load image
loadingBulletInProgress = 1;
//Stop this for() loop while we load image
i = 999;
}
}
}
}
private function loadImage(BlackHole:Event){
//Image has loaded; find which array slot it needs to go into
for(var i:Number = 0; i <= bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//We found which array type it belongs to; now replace the text/url location with the actual image data
var tmpNewBullet:MovieClip = new MovieClip;
tmpNewBullet.addChild(mLoader);
//Add image to array
bulletType[i] = tmpNewBullet;
//Restart loadingBullets if there are more left
loadingBulletInProgress = 0;
//Stop for() loop
i = 999;
}
}
}
//###############################################################################################################################################
private function fireBullets(){
//If player is holding down mouse; Fire weapon at rate of fire.
if(shootingWeapon >= 1){
if(bulletFireEvent == null){
//Start shooting bullets
bulletFireEvent = setInterval(allowShooting, 500);
}
}
if(shootingWeapon == 0){
//The user is not shooting so stop all bullets from firing
if(bulletFireEvent != null){
//Strop firing bullets
clearInterval(bulletFireEvent);
bulletFireEvent = null
}
}
}
private function allowShooting(){
//This function actually adds the bullets on screen
//Search for correct bullet/ammo image to attach
var bulletId:Number = 0;
for(var i:Number = 0; i < bulletArray.length; i++){
if(bulletArray[i] == shootingWeapon){
//Bullet found
bulletId = i;
//End For() loop
i = 999;
}
}
//Create new bullet
//Create Tmp Bullet
var tmpBulletId:MovieClip = new MovieClip
tmpBulletId.addChild(newBullet);
tmpBulletId.addChild(bulletType[bulletId]);
//Add To Stage
addChild(tmpBulletId)
bulletContainer.push(tmpBulletId); //Add to array of bullets
//Orientate this bullet from players body
var bulletTmpId:Number = bulletContainer.length
bulletTmpId--;
bulletContainer[bulletTmpId].x = Object(root).localSurvivor.x
bulletContainer[bulletTmpId].y = Object(root).localSurvivor.y
//addChild(bulletContainer[bulletTmpId]);
}
//_______________EXTERNAL EVENTS_______________________
public function fireBullet(weaponId:Number){
shootingWeapon = weaponId;
}
public function stopFireBullets(){
shootingWeapon = 0;
}
}
}
BulletClass:
package com{
import flash.display.*
import flash.utils.*
import flash.net.*
import flash.events.*
public class bulletClass extends MovieClip {
public var damage:Number = 0;
public function bulletClass() {
//SOME MOVEMENT CODE HERE
}
public function addAvatar(Obj:MovieClip){
this.addChild(Obj);
}
}
}
Well ... if I may say so, this code looks quite wrong. Either something is missing from the code or this code will never make the bullets fly.
First off, you can set x and y of the new bullet directly (replace everything after "orientate this bullet from players body" with this):
tmpBulletId.x = Object(root).localSurvivor.x;
tmpBulletId.y = Object(root).localSurvivor.y;
Perhaps this already helps, but your code there should already do the same.
But to let these bullets fly into any direction, you also need to add an event listener, like so:
tmpBulletId.addEventListener(Event.ENTER_FRAME, moveBullet);
function moveBullet(e:Event) {
var movedBullet:MovieClip = MovieClip(e.currentTarget);
if (movedBullet.x < 0 || movedBullet.x > movedBullet.stage.width ||
movedBullet.y < 0 || movedBullet.y > movedBullet.stage.height) {
// remove move listener, because the bullet moved out of stage
movedBullet.removeEventListener(Event.ENTER_FRAME);
}
// remove the comment (the //) from the line that you need
MovieClip(e.currentTarget).x += 1; // move right
// MovieClip(e.currentTarget).y -= 1; // move up
// MovieClip(e.currentTarget).x -= 1; // move left
// MovieClip(e.currentTarget).y += 1; // move down
}
This example lets your bullet fly to the right. If you need it flying into another direction, just comment out the line with the "move right" comment and uncomment one of the other lines.
This is of course a very simple example, but it should get you started.
I hope this helps, and that my answer is not the wrong answer to the question.
As far as I have expirienced it you can have only one copy of MovieClip object added to specific child. Best approach is to use ByteArray for the clip source and instantiate new MovieClip and pass the ByteArray as a source. It have something to do with child/parent relation since a DisplayObject can have only one parent (and a way to detach the object from scene too).
Well i ended up writeing the whole code from scratch for a 3rd time and ran into a similar problem and just for reference to anybody else that comes to a problem thats random as this one i found that problem was likly does to a conversion error somewhere that doesn't necessarily break any compiling rules. Just that i was calling a movieclip and not the class it self.