action script to add a pause button on a few audio buttons - actionscript-3

I am currently using the following code to play audio recordings from the project library.
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.MouseEvent;
var sound1:Sound = new audio1();
var sound2:Sound = new audio2();
var mySoundChannel:SoundChannel = new SoundChannel();
function stopSound():void
{
//This stops all sound in the sound channel.
//If there is nothing playing, nothing happens.
mySoundChannel.stop();
}
//In this function, we create an argument that allows us to tell the function
//what sound to we want it to play.
function playSound(soundname:String):void
{
try
{
mySoundChannel = this[soundname].play(0, 0);
}
catch(error:ReferenceError)
{
trace("playSound: That sound name doesn't exist.");
return;
}
}
//Hook up buttons-->
button1.buttonMode = true;
button1.useHandCursor = true;
button2.buttonMode = true;
button2.useHandCursor = true;
button1.addEventListener(MouseEvent.CLICK, button1click);
button2.addEventListener(MouseEvent.CLICK, button2click);
function button1click(evt:Event):void
{
stopSound();
playSound("sound1");
}
function button2click(evt:Event):void
{
stopSound();
playSound("sound2");
}
I need to pause the currently playing audio when a button is clicked. How do I do this?

You will need to do five things to your current code in order to pause and resume the currently playing sound:
Create a variable that stores the name of the currently playing
sound, and a variable to store the pause position of the audio.
Create a pause function.
Create a resume function.
Expand the current playSound and stopSound functions to work with the new variables.
Hook up the button event listener.
Step 1:
var currentSound:String = "";
var pausePosition:Number = 0;
Step 2: We're going to save the current position of the audio in that second variable we just created. We can get the current play position of the audio using the mySoundChannel.position property, which returns a Number value (matching the Number type we gave the pausePosition variable).
function pauseSound():void
{
//If there's a song to pause...
if(currentSound != "")
{
//Get pause position.
pausePosition = mySoundChannel.position;
//Stop the sound directly.
mySoundChannel.stop();
}
}
Note we didn't call stopSound(). There's a good reason for that. We're going to put an extra line of code in that function shortly that we don't want to use in pauseSound().
Step 3: Now we create the function to resume audio. Note this is NOT the same as playSound(). We're telling it to start playing from pausePosition, not from 0 (the beginning of the sound clip).
function resumeSound():void
{
//If there's a song to resume...
if(currentSound != "")
{
//Start playing the current audio from the position we left off at.
mySoundChannel = this[currentSound].play(pausePosition);
}
}
Step 4: Since we're now working with those variables we declared in step 1, we need to adjust how playSound() and stopSound() work.
In playSound(), instead of just passing soundname to the sound channel, we're going to save the soundname to currentSound.
function playSound(soundname:String):void
{
try
{
currentSound = soundname
mySoundChannel = this[currentSound].play(0, 0);
}
catch(error:ReferenceError)
{
trace("playSound: That sound name doesn't exist.");
return;
}
}
In stopSound(), we need to actually clear the currentSound and pausePosition variables when we stop, to ensure that resumeSound doesn't start audio after we've totally stopped it.
function stopSound():void
{
//This stops all sound in the sound channel.
//If there is nothing playing, nothing happens.
mySoundChannel.stop();
//Clear our variables.
currentSound = "";
pausePosition = 0;
}
GOTCHA WARNING: Ordinarily, you can loop audio by passing an integer other than 0 in the second argument (where I have the 5) in the following code:
mySoundChannel = this[currentSound].play(0, 5);
In the above code, the sound would play from the beginning, and repeat five times.
However, if you are starting the audio from any position other than 0, what will actually happen is that the audio will loop at the position you start at, not at the beginning.
That is to say, if you use this code:
mySoundChannel = this[currentSound].play(1000, 5);
The sound will loop five times, but every time the sound starts over in the loop, it will start playing from position 1000, and NOT the beginning of the sound (0).
I hope that answers your question!

Related

How to STOP looping sound when going into next frame/Errors

I have a flash project broken up into multiple frames, with a button on each frame that goes to play the next frame. (And a movieclip on each frame that plays until you hit next frame button)
On each frame, I want audio to play, and loop.
But, I want the audio from one frame to stop when I click the button to go to the next.
On frame 4, I have this code:
import flash.media.SoundChannel;
var sound:Sound = new firt2();
var soundChannel:SoundChannel;
sound.addEventListener(Event.COMPLETE, onSoundLoadComplete);
sound.play();
function onSoundLoadComplete(e:Event):void{
sound.removeEventListener(Event.COMPLETE, onSoundLoadComplete);
soundChannel = sound.play();
soundChannel.addEventListener(Event.SOUND_COMPLETE, onSoundChannelSoundComplete);
}
function onSoundChannelSoundComplete(e:Event):void{
e.currentTarget.removeEventListener(Event.SOUND_COMPLETE, onSoundChannelSoundComplete);
}
And it works. However, I want to stop it once I click the button to go to the next frame. I have tried:
soundChannel.stop();
On the next frame.
However, whenever I do that, the output reads:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at hhh4_fla::MainTimeline/frame5()
at flash.display::MovieClip/gotoAndPlay()
at hhh4_fla::MainTimeline/fl_ClickToGoToAndPlayFromFrame()
All of my buttons and movieclip have instance names.
Rather than figuring why it doesn't work with all these frames and timelines, I think it's better to compose a centralized sound manager class that handles these things.
Implementation. Keep in mind that I didn't test that so please excuse me for occasional typo if any. The logic of it all should be correct.
package
{
import flash.system.ApplicationDomain;
import flash.media.SoundChannel;
import flash.media.Sound;
import flash.events.Event;
public class Audio
{
// Container to cache Sound objects.
static private const cache:Object = new Object;
// Variables to hold the current values.
static private var currentChannel:SoundChannel;
static private var currentSound:String;
// Stops the current sound playing. If you pass the sound name, it
// will stop the audio track only if it is the exact one playing.
// Otherwise it will stop any one currently playing.
static public function stop(value:String = null):void
{
// Do nothing if nothing is playing right now,
// or if the specific sound requested to stop does not match.
if (currentSound == null) return;
if (value) if (value != currentSound) return;
// Unsubscribe from event and stop the audio.
currentChannel.removeEventListener(Event.SOUND_COMPLETE, onComplete);
currentChannel.stop();
// Final clean-up.
currentChannel = null;
currentSound = null;
}
// Plays the embedded sound by its class name.
static public function play(value:String):void
{
// Do nothing if the requested sound is already playing.
if (value == currentSound) return;
// Stop the current audio track playing.
stop();
// Check if that one sound is valid and/or was previously requested.
if (!cache[value])
{
try
{
// Obtain class definition from the project.
var aClass:Class = ApplicationDomain.currentDomain.getDefinition(value) as Class;
// Try instantiating the Sound.
if (aClass) cache[value] = new aClass as Sound;
}
catch (fail:Error)
{
// Well, do nothing, yet.
}
}
if (cache[value])
{
// Store the id of audio track that is going to be playing.
currentSound = value;
// Play the track and subscribe to it for the SOUND_COMPLETE event.
currentChannel = (cache[value] as Sound).play();
currentChannel.addEventListener(Event.SOUND_COMPLETE, onComplete);
}
else
{
// If there's no such class, or it is not a Sound,
trace("ERROR: there's no sound <<" + value + ">> is embedded into the project.");
}
}
// Event handler to clean up once the current audio track is complete.
static private function onComplete(e:Event):void
{
// Sanity check.
if (e.target != currentChannel) return;
stop();
}
}
}
Usage.
import Audio;
// Any time you want different sound to play.
// Pass the class name as Sting as an argument.
Audio.play("firt2");
// Any time you just want to stop the sound;
Audio.stop();

TotalTime of a stream - Video Flash Player AS3

Goodmorning,
I'm working on a video flash player to stream. What I want to do, is to display the total time of the stream and not the time since the user is watching the stream.
I have a problem now, is that when I pause then play the video, the current time restarts.
Do you have any ideas to fix my problem and to solve the other one? :)
**I'm using NetStream
Alright, for the first problem, what you want to do is to setup a function that receives the MetaData of the video and save that value somewhere.
First, when you create your NetStream Object, you need to add a Client to the NetStream that references the function onMetaData.
var ns:NetStream; //your NetStream Object
var client:Object = new Object(); //Create an Object that represents the client
client.onMetaData = onMetaData; //reference the function that catches the MetaData of the Video
ns.client = client; //assign our client Object to the client property of the NetStream
//Once MetaData is available, it'll call onMetaData with all of the information
function onMetaData(metaData:Object):void
{
duration = metaData.duration; //duration is the variable that is supposed to total length of the video
}
Now with the duration value you get the total play time of the movie that is currently playing with that NetStream Object.
You can solve your second problem in a number of ways, for example:
pause() and resume()
pause() and player('currentTime')
Simply keep a Boolean Variable called pause that keeps track if the video is currently playing or not.
var paused:Boolean = false; //assuming the video is currently playing
var currentTime:Number = 0;
var button:Button; //some kind of play/pause button
button.addEventListener(MouseEvent.CLICK,onButtonClick);
function onButtonClick(event:MouseEvent):void
{
if(paused)
{
paused = false;
ns.resume();
//ns.play(currentTime) //this also works
}
else
{
paused = true;
ns.pause();
currentTime = ns.time;
}
}
You have to extract the information from the meta data of the file.
Thank you for you answers :).
DodgerThud, I tried your solution concerning my second problem this morning. I tried your solution and I've got this : duration : NaN. If I understand well, my problem is that I don't have the metadata of the stream...
if(isLiveStream == false) {
if(title == preroll || Number(duree) <= 0) {
duration=infoObject.duration+timeOffset;
} else {
duration=Number(duree);
}
}
Those lines are on the onMetaData function.
Thank you for helping me.
Have a nice day.

How do I loop and stop a sound using the same button in AS3?

I have 4 buttons on stage and I need a code that enables me to click on one of them, loop a specific sound "infinitely", and when it is clicked again, the sound stops. The sound is not initially playing. Also, while one of the sounds is looping, if I press another button, I'd like the previous sound to stop and the new one to play.
To help visualize this more, I will explain my project. I have to create an 'app' that is like an online guitar tuner. This feature is sort of what I would like to recreate:
http://www.gieson.com/Library/projects/utilities/tuner/
I don't even know where to begin with the coding... any help is greatly appreciated. Thank you!
The actual code is quite dependent on how you are loading in the sound, so I will write the "skeleton" for the code.
var currentSound:Sound = null;
var currentSoundChannel:SoundChannel;
var sound1:Sound = /* Load me */
var sound2:Sound = /* Load me */
button1.addEventListener(MouseEvent.CLICK, playSound1);
function playSound1(event:MouseEvent)
{
playSound(sound1);
}
button2.addEventListener(MouseEvent.CLICK, playSound2);
function playSound2(event:MouseEvent)
{
playSound(sound2);
}
function playSound(sound:Sound):void
{
if (currentSound != null)
{
// Stop the current music
currentSoundChannel.stop();
}
if (currentSound == sound)
{
// Stop playing ANY sound
currentSound = null;
currentSoundChannel = null;
}
else
{
// Play a different sound
currentSound = sound;
currentSoundChannel = sound.play();
}
}

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.

Recyclable Sound Object in Actionscript 3?

Using ONE Sound() object in Actionscript3, how can I play a one MP3 and then, when the user chooses a different one, play a second sound, using the SAME Sound() object?
EDIT: See my answer for how I did it.
You cannot use same Sound object to play multiple files.
Once load() is called on a Sound object, you can't later load a different sound file into that Sound object. To load a different sound file, create a new Sound object.
Ok, I actually did it using the following code. My bug was somewhere else in the FLA file, but this works. I made an uninitialized global variable and created the Sound() object LOCALLY inside of a function. While I'm technically using multiple sound objects, my references are all pointing to ONE object. Additionally, I can call these methods over one another for easier coding. This works for me:
/* -------------
Sound player
functions
------------ */
var snd:Sound; //the sound object
var sndC:SoundChannel; //the soudchannel used as "controller"
var sndT:SoundTransform; //soundTransform used for volume
var vol:Number = 1; //the volume of the song
var pan:Number = 0; //panning of the sound
var pos:Number = 0; //position of the song
var currentSound:String; //currently playing song?
function playSound(s:String){ //this function resets the sound and plays it
stopSound(sndC); //stop the sound from playing
snd = new Sound(); //reset the sound
snd.load(new URLRequest(s)); //load the desired sound
sndC = new SoundChannel(); //(re-)apply the sound channel
applyVolume(vol,pan,sndT,sndC); //apply the volume
sndC = snd.play(pos); //play it
sndC.addEventListener(Event.SOUND_COMPLETE, startSound); //remind it to restart playing when it's done
} //end function
function applyVolume(n:Number, p:Number, st:SoundTransform, sc:SoundChannel){ //takes an argument for the volume, pan, soundTYransform and soundChannel
sndT = new SoundTransform(n,p); //applies the soundTransfrom settings
sndC.soundTransform = sndT; //and attaches it to the soundChannel
} //end function
function stopSound(sndC:SoundChannel){ //this function stops a sound from playing
if(sndC != null){ //if the sound was used before (ie: playing)
if(currentLabel == "video-frame"){ //if we are in the video frame
pos = sndC.position; //store the position of the song to play from at a later time
}else{ //otherwise
pos = 0; //set the position at 0
} //end if
sndC.stop(); //stop it
} //end if
} //end function
function startSound(snd:Sound){ //restarts a sound when it's playing
if(snd != null){ //if the sound exists
sndC = snd.play(pos); //play it
} //end if
} //end function