Play/stop sound on one button (AS3)

hello
when you click the first time on the button, it should start the song, when you click a second time on the button, it should stop the song. how do i make this with actionscript 3?
regards
simon

A very basic example:
You'd need 3 var:
private var _sound:Sound;
private var _soundChannel:SoundChannel;
private var _soundChannelPosition:Number = 0;
Then create a Sound:
_sound = new Sound(new URLRequest("some.mp3"));
Stop/play the sound on click:
        private function click(e:MouseEvent):void {
            if(_soundChannel == null){
                _soundChannel = _sound.play(_soundChannelPosition);
            } else {
                _soundChannelPosition = _soundChannel.position;
                _soundChannel.stop();
                _soundChannel = null;

Similar Messages

  • How do i play two sound file one after another

    Hi All,
    How do i play two sound file one after another using single AudioClip Component?.
    Advance in thanks
    Manivel

    AudioClip gives you very little control over what happens to the sound, it also isn't capable of playing long clips or waiting until a clip ends. It will play multiple clips over top of each other.
    To do what you want you should use the facilities of javax.sound. Here's a post with an example: http://forum.java.sun.com/thread.jspa?forumID=513&threadID=450768
    There is also a tutorial, but its example fails for long clips.

  • Multiple sounds in one button

    would you kindly give me a suggestion that how to make multiple sounds in a button of a windows form application. actually, being a newb i'm trying to develop a piano application by C# for my own interest. the problem is, when i press one button it plays
    too long & i had to wait until the wav file is finished & after that i had to press another button. what's the code for playing multiple sounds together in one button? u know, then i can play chords too. would you kindly explain or give a code?

    Hi Rinku,
    This is an example for you:
    A Piano Key Control in C#
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Stop sound of a button

    Hi..
    I have a bit of a problem with sound.. I have a main container animation with background sound that's loaded with soundChannel..
    I also have an externally loaded SWFs with Movie Clip buttons that have a sound ON ROLLOVER on the timeline..after rolling off - I place the:
    SoundMixer.stopAll(); to stop the button from playing the sound once the mouse is rolled off.. However, the problem I'm running into is that it also stops the sound of the main container movie clip - any suggestions? Thanks a bunch ahead of time!

    This sound is still giving me problems... agghh... it works well if you mouse over once or twice - but if I mouse over the button over and over, it gets stuck..
    The below code is inside a Movie Clip. The MovieClip is stoped at frame 1. When you mouseover the movie clip, it goes to frame 2. That's where I put the following script. On MouseOut it goes and stops on Frame 3..
    Any help would be super appreciated - thanks ahead of time!
    var blendSound:Blend = new Blend();
    var scChannel:SoundChannel = new SoundChannel();
    var b:Boolean;
    if(!b) {
    function stopSoundHandler(evt:MouseEvent):void {
        scChannel.stop();
    btn.addEventListener(MouseEvent.MOUSE_OUT, stopSoundHandler);
    btn.addEventListener(MouseEvent.MOUSE_DOWN, stopSoundHandler);
    btn.addEventListener(MouseEvent.MOUSE_UP, stopSoundHandler);
    scChannel = blendSound.play();

  • Play two MCs with one button

    Hi,
    I'm trying to make the main timeline go to frame 2, and a separate MC go to frame 2 by clicking one button.
    Here's what I'm trying ...
    on (release) {
        _root.gotoAndPlay(2);
        snap1.gotoandplay(2);
    When the button is clicked, the main timeline goes to frame 2, but the MC (instance name) snap1, doesn't play. I'm using AS2.

    actionscript is case-sensitive.  use:
    on (release) {
        _root.gotoAndPlay(2);
        snap1.gotoAndplay(2);

  • Stop sound when same button is pressed

    I'm a complete beginner to any type of programming, so I'm glad that I even got this small tiny script working without errors. I've been scouring the web for tutorials and help and I can't find any tutorial to help. But I know this is a Programming 101 fix, so if anyone
    wants to give me any advice, I'd gladly appreciate it.
    When I press Btn1 - a sound plays, BUT when i press another button (either Btn2 or Btn1 again) then the sounds overlap each other. Can someone help me
    Write an if statement such that when a second button is pressed that the first sound will STOP playing?  Here is what I have, I know my URLRequest could be simplified...but it works and thats all I care about right now.
    Thanks in advance!
    -David

    David,
    I am not an expert, but it looks like you just need to add a line ahead of the new request into each of your 2 functions
    channel = sound.stop();
    req = new URLRequest("/assets/song1.mp3");
                                            sound = new Sound(req);
                                            channel = sound.play();
    BR
    peter

  • One button for sound start & stop Flash AS3

    Hi,
    I am trying to create a sound button to start a sound and then stop it when clicked again.
    I thought it would be easy because there is a code snippet for "click to play/stop sound"
    I have my sound file in my library.
    Below is the code that is not working:
    Instructions:
    1. Replace "http://www.helpexamples.com/flash/sound/song1.mp3" below with the desired URL address of your sound file. Keep the quotation marks ("").
    CYOA2bttn.addEventListener(MouseEvent.CLICK, fl_ClickToPlayStopSound_11);
    var fl_SC_11:SoundChannel;
    //This variable keeps track of whether you want to play or stop the sound
    var fl_ToPlay_11:Boolean = true;
    Proxy-Connection: keep-alive Cache-Control: max-age=0 Cp>function fl_ClickToPlayStopSound_11(evt:MouseEvent):void
        if(fl_ToPlay_11)
            var s:Sound = new Sound(new URLRequest("CYOA2.wav"));
            fl_SC_11 = s.play();
        else
            fl_SC_11.stop();
        fl_ToPlay_11 = !fl_ToPlay_11;
    CYOA2bttn is my button and CYOA2.wav is my sound file.
    The error that comes up when I try to test the Flash file is:
    Error #2044: Unhandled IOErrorEvent:. text=Error #2032: Stream Error.
        at CYOA_fla::MainTimeline/fl_ClickToPlayStopSound_11()
    ANY SUGGESTIONS!?
    Help PLEASE

    hi
    if the mp3 is in your library (in your fla) then the code is slightly different...
    first, right-click on the sound in the library and select properties. Then tick "Export for ActionScript", and enter a name in "Class" (eg: mySound).
    Then amend your code:
    replace:
    var s:Sound = new Sound(new URLRequest("CYOA2.wav"));
    with:
    var s:Sound = new mySound();
    (replace "mySound" with whatever you entered for "Class" above.

  • Stop sound when another sound plays

    Hey guys,
    Using Flash Pro CC 2014, Actionscript 3
    I am working on a soundboard and use buttons that play sounds, and I want to make it that when a new sound plays, it automatically stops the current sound from playing, that way 2 sounds dont play at same time.
    But I also have a button that stops all sounds, I am using the "Click to Stop All Sounds" code under Audio and Video in the Code Snippets.
    So I am basically wanting to make sure I can do both, keep the stop all sounds button, but also have it when you press any sound button, it stops all sounds and starts playing the current button/sound. Any suggestions?
    BTW I am setting up symbols as buttons, not movie clips incase you need to know for coding, but I can switch to movie clips if its easier. I was just used to buttons on older versions of Flash for simple stuff like this.
    Thanks.

    Thanks for the reply, I am new to actionscript 3 but am a fast learner. Maybe I am doing this wrong, but when I add the code it simply stops the sounds, but it wont play the sound from the button that I just clicked on. I want it to play the sound button clicked on, and also stop any other sounds that are currently playing.
    For Flash 8, as2, I would add this to the button:
    on (press)
        stopAllSounds ();
    On as3, does it need to say this?
    button_2.addEventListener(MouseEvent.CLICK, fl_ClickToStopAllSounds);
    function fl_ClickToStopAllSounds(event:MouseEvent):void
        SoundMixer.stopAll();
    thanks for your help

  • I'm trying to play Symbol A and it's nested Symbol B and C with one button, and play Symbol B and C without playing Symbol A with a second button...

    I can't seem to get the nested symbol to play without it's parent playing too.
    This works for getting both symbols to play on button 1
    sym.getComposition().getStage().getSymbol("marketing_buttons").getSymbol("online").play();
    sym.getComposition().getStage().getSymbol("marketing_buttons").getSymbol("promotions").pla y();
    Everything I've done to play just B and C play all three. Is what I'm trying to do even possible?
    Thanks in advance.
    -h

    sym.getComposition().getStage().getSymbol("marketing_buttons").getSymbol("online").play();
    sym.getComposition().getStage().getSymbol("marketing_buttons").getSymbol("promotions").pla y();
    This works now to play all three from one button. With a different button, I want to play just the nested "online" and "promotions", plus add an completely new animation to both. All without effecting the animation in "marketing_buttons".

  • Mainstage + NanoPad: how assign sound to every button?

    Hello men!
    I need your help. I use mainstage 2.0.1 with my master keyboard cme m-key AND my new Korg nanoPad. I have created patch sounds in mainstage and I want to assign every sound to one button of my nanopad.
    Example:
    1- Strings
    2- Piano
    3- Choir
    when I press 1 on my nanopad mainstage plays strings, when I press 2 plays piano ecc. I read on internet that I need a learn mode but I can't do that
    Can you help me? I made a workaround assign 2 button to prev and next patch but It is just a workaround I put my nanopad on program change and control change without success.
    Thank you in advance.

    {quote:title=PaoloMactux wrote:} I use mainstage 2.0.1 with my master keyboard cme m-key AND my new Korg nanoPad. I have created patch sounds in mainstage and I want to assign every sound to one button of my nanopad.
    Example:
    1- Strings
    2- Piano
    3- Choir
    when I press 1 on my nanopad mainstage plays strings, when I press 2 plays piano ecc. I read on internet that I need a learn mode but I can't do that
    {quote}
    I think that the Learn you are looking for is in the MS Layout window.
    Click on a button in your layout to select it.
    click on the Learn button in the Inspector frame
    press the button on your hardware three times
    select the next button in the layout
    press the button on your hardware three times/
    Repeat as necessary.

  • Problem with playing a sound file.

    Hi,
    I simply want to play a sound by a button click. I imported
    <AVFoundation/AVAudioPlayer.h>. The code block is here:
    In .h file:
    #import <UIKit/UIKit.h>
    #import <AVFoundation/AVAudioPlayer.h>
    @interface PlaySoundViewController : UIViewController <AVAudioPlayerDelegate>
    in .m file:
    -(IBAction)btnPlay:(id)sender
        //Get the filename of the sound file:
        NSString *path = [[NSBundle mainBundle] pathForResource:@"REC001" ofType:@"MP3"];
        AVAudioPlayer* thePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];//error here as it will compile if I commented it (and two line after) out.
        thePlayer.delegate = self;
        [thePlayer play];   
    Everything looks fine but it failed when I tried to run it. Looks like it cannot find my sound file "REC001.MP3". I put it in folder ".../PlaySound/Resource Files/SoundFiles/REC001.MP3", and "PlaySound" is my project name. However the path returned is ".../PlaySound/REC001.MP3". I guess this is why it cannot find the object. But it didn't work even I put the sound file under "PlaySound" directly. Anyone has a solution?
    Thanks.
    Regards,
    Taizhi

    Hi Mark,
    Thanks for the reply. Based on your instruction, I checked and I can see the sound files in Build Phases. The location is ".../PlaySound/SoundFiles/REC001.MP3". I don't know why it ignores folder "Resource Files". I guess that is the way it is as I also can see other images in different folders which are shown properly in the project.
    The detailed error message is here:
    Ld "/Users/greatzhi2001/Library/Developer/Xcode/DerivedData/PlaySound-anydnuuxbpxz lqfodwbuqqjwjzcd/Build/Products/Debug-iphonesimulator/PlaySound.app/PlaySound" normal i386
        cd "/Users/greatzhi2001/Desktop/iProjects/PlaySound"
        setenv MACOSX_DEPLOYMENT_TARGET 10.6
        setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr /bin:/usr/bin:/bin:/usr/sbin:/sbin"
        /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3 .sdk -L/Users/greatzhi2001/Library/Developer/Xcode/DerivedData/PlaySound-anydnuuxbpx zlqfodwbuqqjwjzcd/Build/Products/Debug-iphonesimulator -F/Users/greatzhi2001/Library/Developer/Xcode/DerivedData/PlaySound-anydnuuxbpx zlqfodwbuqqjwjzcd/Build/Products/Debug-iphonesimulator "-F/Users/greatzhi2001/Desktop/iProjects/PlaySound" -filelist "/Users/greatzhi2001/Library/Developer/Xcode/DerivedData/PlaySound-anydnuuxbpxz lqfodwbuqqjwjzcd/Build/Intermediates/PlaySound.build/Debug-iphonesimulator/PlayS ound.build/Objects-normal/i386/PlaySound.LinkFileList" -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework UIKit -framework Foundation -framework CoreGraphics -o "/Users/greatzhi2001/Library/Developer/Xcode/DerivedData/PlaySound-anydnuuxbpxz lqfodwbuqqjwjzcd/Build/Products/Debug-iphonesimulator/PlaySound.app/PlaySound"
    Undefined symbols for architecture i386:
      "_OBJC_CLASS_$_AVAudioPlayer", referenced from:
          objc-class-ref in PlaySoundViewController.o
    ld: symbol(s) not found for architecture i386
    collect2: ld returned 1 exit status
    Is the framework AVFoundation I added wrong? Thanks.
    Regards,
    Taizhi

  • Playing mp4 sound files

    I am trying to make my code play a sound when a button is pressed. 
    At the moment I am using the play sound file block, but this block only accepts files in a .WAV format. 
    I am creating this program for someone who is not great with computers. Their easiest way to record sounds to be played saves them in an MP4 format.
    Having to make them convert the files to .WAV would be very difficult and frustraiting for them.
    What I am asking is if there is a way to play a MP4 file in labview, or a way to programatically convert a MP4 file into a .WAV file for the play sound file block.
    Thanks for your time. 

    This might work.
    Attachments:
    WindowsMedia_Player.vi ‏148 KB

  • My new iPod plays the music over and over again. It does not stop and the volume buttons have no effect. What can I do? The RESTRICTIONS  require a a passcode and I don't have one. Any suggestions?

    My new iPod plays the music over and over again. It does not stop and the volume buttons have no effect. What can I do? The RESTRICTIONS  require a a passcode and I don't have one. Any suggestions?

    Try:
    - Reset the iOS device. Nothing will be lost       
    Reset iOS device: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Unsync/delete all music and resync
    - Reset all settings      
    Go to Settings > General > Reset and tap Reset All Settings.
    All your preferences and settings are reset. Information (such as contacts and calendars) and media (such as songs and videos) aren’t affected.
    - Restore from backup.
    In order to restore with the unknown Restrictions passcode you will likely have to place the iPod in Recovery Mode and then connect to your computer and restore via iTunes. The iPod will be erased.
    If recovery mode does not work try DFU mode.                        
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings        
    For how to restore:
    iTunes: Restoring iOS software
    To restore from backup see:
    iOS: Back up and restore your iOS device with iCloud or iTunes
    - Last,
    - Restore to factory settings/new iOS device.      

  • How do I stop sound from playing when I leave frame?

    I have designed a website for an advertising agency using
    Flash and ActionScript 3. In the portfolio page, I have several TV
    commercials that are available to play. What I need is 1) when the
    user leaves the TV ad page, I want the tv commercial to quit
    playing (right now, it continues even though the user has moved on
    to other pages). and 2) If the user selects a different TV
    commercial without first stopping the original one, the sound for
    both of the them plays at the same time. I am using the flv
    playback component. The video appears to stop, but the sound
    doesn't. My TV commercials are external flv files.
    I have also made a page for radio ads and I just used play,
    pause and stop buttons to control the sound. This page does the
    same thing. The sound continues when you move on to another page in
    the site. My sound files are also all external sound files.
    All of my pages are just individual frames in a main
    timeline. Each page has a frame label.
    If this is not clear, here is the link to my site:
    http://www.hammockads.com
    I would appreciate any help anyone can give me with this. I
    have tried for weeks now, to solve this problem and I just don't
    know enough actionscript or flash to figure it out. I've only been
    working with this for a few months.

    I have my website set up so that the portfolio page occupies
    one frame of my timeline. Inside that frame, I have a movie clip
    which contains the additional pages of the portfolio section. The
    additional pages show examples of the print ads, radio ads, tv ads,
    web sites that my client has created. Each of these additional
    pages is also one frame of the timeline (this time inside the
    portfolio movie clip). When the user clicks a link in the website,
    it just takes them to another frame on my timeline.
    The entire website is one swf file and each of the pages is
    located on one frame of the timeline (either on the main timeline
    or inside a movie clip timeline.)
    In the tv ads page, I have a button for each of the tv
    commercials. When the user selects a specific commercial, then the
    actionscript calls that particular ad from an external flv file.
    The problem is that when the user clicks another button (to view
    another ad or chooses to go to another page in the website (which
    involves leaving the current frame in the timeline) the video or
    radio ad doesn't automatically stop playing.
    I can't really post code, because I'm not sure what code to
    post. The TV ads are currently set up using the FLV playback
    feature. The radio ads are set up with play, stop, pause and volume
    control buttons. When a user here selects a new radio ad, the one
    currently playing stops and the new one starts, but when the user
    chooses to go to another page without first stopping the ad from
    playing, it continues to play.
    On the TV ads page, nothing is really working except that the
    ad plays and stops when it comes to the end. I'm thinking that I
    may need to go back and re-code the TV ads to play without using
    the flv playback option.
    Any thoughts? I hope this is a little bit clearer.

  • Flash CS3 Play/Stop audio button problem

    I made a play/stop audio button with this youtube tutorial (youtube.com/watch?v=XU6oMEFUFF8) but after the sound is finished I want the play button to show up agian.
    Here is the actionscript:
    import flash.events.MouseEvent;
    play_btn.addEventListener(MouseEvent.CLICK,clickha ndler);
    stop_btn.addEventListener(MouseEvent.CLICK,clickha ndler);
    function clickhandler(event:MouseEvent):void{
    swapChildren(play_btn,stop_btn);
    what code should I add to my current code?
    I also can send you the Fla.

    You should consider using the Sound class. Here's a quick overview of it:
    http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7d21.html
    You'll be able to add event listeners to the sound to know when it completes so you can execute more code, such as swapping the play and stop button. There is an example in that overview of listening for the SOUND_COMPLETE event (e.g. channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);). It should contain everything you need.
    A basic example of what you'll end up with (there's many ways to do it) might look something like this:
    // just set up and wait for click
    var isPlaying:Boolean = false;
    var mySound:Sound = new MySoundInLibrary();
    var myChannel:SoundChannel = new SoundChannel();
    myChannel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
    // buttons
    play_btn.addEventListener(MouseEvent.CLICK,clickhandler);
    stop_btn.addEventListener(MouseEvent.CLICK,clickhandler);
    function clickhandler(event:MouseEvent):void
              swapChildren(play_btn, stop_btn);
              if (isPlaying)
                        isPlaying = false;
                        myChannel.stop();
              else
                        isPlaying = true;
                        myChannel = mySound.play();
    function onPlaybackComplete(e:Event):void
              isPlaying = false;
              swapChildren(play_btn, stop_btn);
    The basic idea is keeping a flag if the audio is currently playing. If it isn't then assign the sound to a channel and play it while setting the flag (isPlaying) to true. If it's already playing, set the flag to false and stop playing the audio.
    The swapChildren is run in the onPlaybackComplete() method so when the audio completes the play button is swapped back in front.
    Rather than swapping the children I'd urge you to toggle the .visible property instead. It's easy to run commands in the wrong order and get desynched on depth.

Maybe you are looking for

  • Is there a fuction call "on change of group" in CR2008?

    i want to summarize a field of the first record in each group, and than display the result in the report header. using "running total field" can summarize it but only calculated the first record if placing the result in the report header. i want to m

  • Itunes Library and ID3 tags

    Hi, So here's my problem : I spent hours cleaning my MP3 collection and re-Writing ID3 tags in order to have a clean Itunes Library without "Blink 182" and "Blink-182" (for exemple) in the Explorer but just "Blink 182". And importing my tied up music

  • I can't see my music videos

    Can hear playing but can not find video, can hear music.

  • What's happened to the ratings?

    They've gone down dramatically!! -+-No longer a forum member-+-

  • How to create simple timer ?

    how to insert a simple timer to this code ? void jButton4_actionPerformed(ActionEvent e) { jLabel1.setText("Loading .."); // insert timer here setGetShow("A","t4d"," ","1"); jLabel1.setText("Done."); }