flash.media

# SoundChannel - AS3

Package | flash.media
Class | public final class SoundChannel
Inheritance | SoundChannel EventDispatcher Object

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

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

More examples

Playing sounds

Related API Elements

Sound
SoundTransform

Public Properties
Hide Inherited Public Properties
Show Inherited Public Properties

| Property | Defined By
--- | --- | ---
|  | constructor : 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
|  | rightPeak : Number [read-only] The current amplitude (volume) of the right channel, from 0 (silent) to 1 (full amplitude). | SoundChannel
|  | soundTransform : flash.media:SoundTransform The SoundTransform object assigned to the sound channel. | SoundChannel

Public Methods
Hide Inherited Public Methods
Show Inherited Public Methods

| Method | Defined By
--- | --- | ---
|  | 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
|  | dispatchEvent(event:Event):Boolean Dispatches an event into the event flow. | EventDispatcher
|  | hasEventListener(type:String):Boolean Checks whether the EventDispatcher object has any listeners registered for a specific type of event. | EventDispatcher
|  | hasOwnProperty(name:String):Boolean Indicates whether an object has a specified property defined. | Object
|  | isPrototypeOf(theClass:Object):Boolean Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter. | Object
|  | propertyIsEnumerable(name:String):Boolean Indicates whether the specified property exists and is enumerable. | Object
|  | removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void Removes a listener from the EventDispatcher object. | EventDispatcher
|  | setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void Sets the availability of a dynamic property for loop operations. | Object
|  | stop():void Stops the sound playing in the channel. | SoundChannel
|  | toLocaleString():String Returns the string representation of this object, formatted according to locale-specific conventions. | Object
|  | toString():String Returns the string representation of the specified object. | Object
|  | valueOf():Object Returns the primitive value of the specified object. | Object
|  | willTrigger(type:String):Boolean Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. | EventDispatcher

Events
Click for more information on events
Hide Inherited Events
Show Inherited Events

| Event | Summary | Defined By
--- | --- | --- | ---
|  | activate | [broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active. | EventDispatcher
|  | deactivate | [broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive. | EventDispatcher
|  | soundComplete | Dispatched when a sound has finished playing. | SoundChannel

Property Detail

### leftPeak

property

`leftPeak:Number` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

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

Implementation
`public function get leftPeak():Number`

### position

property

`position:Number` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

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`

### rightPeak

property

`rightPeak:Number` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

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

Implementation
`public function get rightPeak():Number`

### soundTransform

property

`soundTransform:flash.media:SoundTransform`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

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():flash.media:SoundTransform`
`public function set soundTransform(value:flash.media:SoundTransform):void`

Related API Elements

SoundTransform
Method Detail

### stop

()
method

`public function stop():void`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

Stops the sound playing in the channel.

Example ( How to use this 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.

Copy

    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

### soundComplete

Event

Event Object Type: `flash.events.Event`
property Event.type = `flash.events.Event.SOUND_COMPLETE`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

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:

Property | Value
--- | ---
`bubbles` | `false`
`cancelable` | `false`; there is no default behavior to cancel.
`currentTarget` | The object that is actively processing the Event object with an event listener.
`target` | The SoundChannel object in which a sound has finished playing.

Example ( How to use this 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.

Copy

    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 How to use this example
SoundChannelExample.as
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.
Copy

    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();
            }
        }
    }

© 2015 Adobe Systems Incorporated. All rights reserved.
Mon Apr 10 2017, 12:28 PM -07:00