Packageflash.media
Classpublic final class SoundChannel
InheritanceSoundChannel Inheritance EventDispatcher Inheritance Object

Language version: ActionScript 3.0
Runtime version: 

The SoundChannel class controls a sound in an application. Every sound is assigned to a sound channel, and the application can have multiple sound channels that are mixed together. The SoundChannel class contains a stop() method, properties for monitoring the amplitude (volume) of the channel, and a property for assigning a SoundTransform object to the channel.

View the examples.

See also

Sound
SoundTransform


Public Properties
 PropertyDefined by
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  leftPeak : Number
[read-only] The current amplitude (volume) of the left channel, from 0 (silent) to 1 (full amplitude).
SoundChannel
  position : Number
[read-only] When the sound is playing, the position property indicates in milliseconds the current point that is being played in the sound file.
SoundChannel
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  rightPeak : Number
[read-only] The current amplitude (volume) of the right channel, from 0 (silent) to 1 (full amplitude).
SoundChannel
  soundTransform : SoundTransform
The SoundTransform object assigned to the sound channel.
SoundChannel
Public Methods
 MethodDefined by
 Inherited
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.
EventDispatcher
 Inherited
Dispatches an event into the event flow.
EventDispatcher
 Inherited
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
  
Stops the sound playing in the channel.
SoundChannel
 Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
 Inherited
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
Events
 EventSummaryDefined by
 Inherited [broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active.EventDispatcher
 Inherited [broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
   Dispatched when a sound has finished playing.SoundChannel
Property detail
leftPeakproperty
leftPeak:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: 

The current amplitude (volume) of the left channel, from 0 (silent) to 1 (full amplitude).

Implementation
    public function get leftPeak():Number
positionproperty 
position:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: 

When the sound is playing, the position property indicates in milliseconds the current point that is being played in the sound file. When the sound is stopped or paused, the position property indicates the last point that was played in the sound file.

A common use case is to save the value of the position property when the sound is stopped. You can resume the sound later by restarting it from that saved position.

If the sound is looped, position is reset to 0 at the beginning of each loop.

Implementation
    public function get position():Number
rightPeakproperty 
rightPeak:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: 

The current amplitude (volume) of the right channel, from 0 (silent) to 1 (full amplitude).

Implementation
    public function get rightPeak():Number
soundTransformproperty 
soundTransform:SoundTransform  [read-write]

Language version: ActionScript 3.0
Runtime version: 

The SoundTransform object assigned to the sound channel. A SoundTransform object includes properties for setting volume, panning, left speaker assignment, and right speaker assignment.

Implementation
    public function get soundTransform():SoundTransform
    public function set soundTransform(value:SoundTransform):void

See also

Method detail
stop()method
public function stop():void

Language version: ActionScript 3.0
Runtime version: 

Stops the sound playing in the channel.


Example
In the following example, the user can pause and replay a sound file.

In the constructor, the sound file is loaded. (This example assumes that the file is in the same directory as the SWF file.) A text field is used as a button for the user to play or pause the sound. When the user selects the button text field, the clickHandler() method is invoked.

In the clickHandler() method, the first time the user selects the text field, the sound is set to play and is assigned to a sound channel. Next, when the user selects the text field to pause, the sound stops playing. The sound channel's position property records the position of the sound at the time it was stopped. This property is used to resume the sound starting at that position, after the user selects the text field to start playing again. Each time the Sound.play() method is called, a new SoundChannel object is created and assigned to the channel variable. The Sound object must be assigned to a SoundChannel object in order to use the sound channel's stop() method to pause the sound.


package {
    import flash.display.Sprite;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.text.TextField;
    import flash.events.MouseEvent;
    import flash.text.TextFieldAutoSize;
            
    public class SoundChannel_stopExample extends Sprite {
        private var snd:Sound = new Sound();
        private var channel:SoundChannel = new SoundChannel();
        private var button:TextField = new TextField();

        public function SoundChannel_stopExample() {
            var req:URLRequest = new URLRequest("MySound.mp3");
            snd.load(req);
            
            button.x = 10;
            button.y = 10;
            button.text = "PLAY";
            button.border = true;
            button.background = true;
            button.selectable = false;
            button.autoSize = TextFieldAutoSize.CENTER;

            button.addEventListener(MouseEvent.CLICK, clickHandler);

            this.addChild(button);
        }

        private function clickHandler(e:MouseEvent):void {
            var pausePosition:int = channel.position;

            if(button.text == "PLAY") {
                channel = snd.play(pausePosition);
                button.text = "PAUSE";
            } 
            else {
                channel.stop();
                button.text = "PLAY";
            }
        }
    }
}

Event detail
soundCompleteevent 
Event object type: flash.events.Event
Event.type property = flash.events.Event.SOUND_COMPLETE

Language version: ActionScript 3.0
Runtime version: 

Dispatched when a sound has finished playing.

The Event.SOUND_COMPLETE constant defines the value of the type property of a soundComplete event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe SoundChannel object in which a sound has finished playing.

Example
In the following example, the user selects songs from a playlist, and then selects Play to play the song in the order selected.

In the constructor, a text field is defined that holds the song list and a line for the selection to play. (Usually, buttons are used for play and list boxes for a song list.) A text format object is defined that changes the format of the song lines to italic after they are selected. When a user selects the text field, the clickHandler() method is invoked.

In the clickHandler() method, the getLineIndexAtPoint() method of the text field object returns the index of the line that the user selected. Using the line index, the getLineText() method gets the content of the text. The if statement checks whether the user selected to play a song or add a song to the play list. If a user selected to play and a song has been selected, then the event listener for mouse click is removed and the playNext() method is called to begin playing the songs. If the user selected a song title, the content of the line is added to the songList array and the format of the line is set to italic.

The playNext() method iterates through the array list to load and play each song. The song is also assigned to a sound channel. An event listener for the sound channel is added to respond when the song finishes playing and the Event.SOUND_COMPLETE event is dispatched. The soundCompleteHandler() method then invokes the playNext() method to play the next song. This process continues until all the songs listed in the array finish playing.

package {
    import flash.display.Sprite;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.events.MouseEvent;
    import flash.text.TextFormat;
    import flash.net.URLRequest;
    import flash.events.Event;
    import flash.events.IOErrorEvent;

    public class SoundChannel_event_soundCompleteExample extends Sprite {
        private var channel:SoundChannel = new SoundChannel();
        private var songList:Array = new Array();
        private var listTextField:TextField = new TextField();
        private var songFormat:TextFormat = new TextFormat();
        private var arrayIndex:int = 0;
        private var songSelected:Boolean = false;
        
        public function SoundChannel_event_soundCompleteExample() {
            
            listTextField.autoSize = TextFieldAutoSize.LEFT;
            listTextField.border = true
            listTextField.background = true;
            listTextField.text = "Song1.mp3\n" + "Song2.mp3\n" 
                                + "Song3.mp3\n" + "Song4.mp3\n" + "PLAY";
        
            songFormat.italic = true;
 
            listTextField.addEventListener(MouseEvent.CLICK, clickHandler);
                        
            addChild(listTextField);
        }
        
        private function clickHandler(e:MouseEvent):void {
            var index:int = listTextField.getLineIndexAtPoint(e.localX, e.localY);
            var line:String = listTextField.getLineText(index);
            var firstIndex:uint = listTextField.getLineOffset(index);
            var playLine:uint = listTextField.numLines - 1;

                if((index == playLine) && (songSelected == true)) {
                    listTextField.removeEventListener(MouseEvent.CLICK, clickHandler);
                    playNext();       

                } else if (index != playLine) {
                     songList.push(line.substr(0, (line.length - 1)));
                     listTextField.setTextFormat(songFormat, firstIndex, 
                                (firstIndex + listTextField.getLineLength(index)));     
                    songSelected = true;
                 }
        }

        private function playNext():void {
 
             if(arrayIndex < songList.length) {
                var snd:Sound = new Sound();
                snd.load(new URLRequest(songList[arrayIndex]));
                channel = snd.play();
                
                channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
                arrayIndex++;
 
            } else {
                songSelected = false;
                    
                while(arrayIndex > 0) {
                    songList.pop();
                    arrayIndex--;
                }
            }
        }    

        private function soundCompleteHandler(e:Event):void {
            playNext();
        }

        private function errorHandler(errorEvent:IOErrorEvent):void {
            trace(errorEvent.text);
        }
    }
}

Examples
examples\SoundChannelExample
The following example loads an MP3 file, plays it, and displays information about sound events that take place as the MP3 file is loaded and played. A Timer object provides updated information about the position of the playhead every 50 milliseconds. To run this example, place a file named MySound.mp3 in the same directory as your SWF file.
package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.net.URLRequest;
    import flash.utils.Timer;

    public class SoundChannelExample extends Sprite {
        private var url:String = "MySound.mp3";
        private var soundFactory:Sound;
        private var channel:SoundChannel;
        private var positionTimer:Timer;

        public function SoundChannelExample() {
            var request:URLRequest = new URLRequest(url);
            soundFactory = new Sound();
            soundFactory.addEventListener(Event.COMPLETE, completeHandler);
            soundFactory.addEventListener(Event.ID3, id3Handler);
            soundFactory.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            soundFactory.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            soundFactory.load(request);

            channel = soundFactory.play();
            channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);

            positionTimer = new Timer(50);
            positionTimer.addEventListener(TimerEvent.TIMER, positionTimerHandler);
            positionTimer.start();
        }
        

        private function positionTimerHandler(event:TimerEvent):void {
            trace("positionTimerHandler: " + channel.position.toFixed(2));
        }

        private function completeHandler(event:Event):void {
            trace("completeHandler: " + event);
        }

        private function id3Handler(event:Event):void {
            trace("id3Handler: " + event);
        }

        private function ioErrorHandler(event:Event):void {
            trace("ioErrorHandler: " + event);
            positionTimer.stop();       
        }

        private function progressHandler(event:ProgressEvent):void {
            trace("progressHandler: " + event);
        }

        private function soundCompleteHandler(event:Event):void {
            trace("soundCompleteHandler: " + event);
            positionTimer.stop();
        }
    }
}