flash.media

# SoundMixer - AS3

Package | flash.media
Class | public final class SoundMixer
Inheritance | SoundMixer Object

Language Version: | ActionScript 3.0

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

The SoundMixer class contains static properties and methods for global sound control in the application. The SoundMixer class controls embedded and streaming sounds in the application, as well as dynamically created sounds (that is, sounds generated in response to a Sound object dispatching a `sampleData` event).

Public Properties
Hide Inherited Public Properties
Show Inherited Public Properties

| Property | Defined By
--- | --- | ---
|  | audioPlaybackMode : String [static] Specifies the audio playback mode of all Sound objects. | SoundMixer
|  | bufferTime : int [static] The number of seconds to preload an embedded streaming sound into a buffer before it starts to stream. | SoundMixer
|  | constructor : Object A reference to the class object or constructor function for a given object instance. | Object
|  | soundTransform : flash.media:SoundTransform [static] The SoundTransform object that controls global sound properties. | SoundMixer
|  | useSpeakerphoneForVoice : Boolean [static] Toggles the speakerphone when the device is in voice mode. | SoundMixer

Public Methods
Hide Inherited Public Methods
Show Inherited Public Methods

| Method | Defined By
--- | --- | ---
|  | areSoundsInaccessible():Boolean [static] Determines whether any sounds are not accessible due to security restrictions. | SoundMixer
|  | computeSpectrum(outputArray:ByteArray, FFTMode:Boolean = false, stretchFactor:int = 0):void [static] Takes a snapshot of the current sound wave and places it into the specified ByteArray object. | SoundMixer
|  | 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
|  | setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void Sets the availability of a dynamic property for loop operations. | Object
|  | stopAll():void [static] Stops all sounds currently playing. | SoundMixer
|  | 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

Property Detail

### audioPlaybackMode

property

`audioPlaybackMode:String`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 3

Specifies the audio playback mode of all Sound objects. On mobile devices, this property sets sound priorities and defaults according to platform idioms. In desktop and TV environments, no functional difference exists between audio playback modes.

Valid values for this property are defined in the AudioPlaybackMode class.

Note On iOS, if one application sets `audioPlaybackMode=AudioPlaybackMode.VOICE`, other applications cannot change it to `AudioPlaybackMode.MEDIA`.

Make the minimum usage of `AudioPlaybackMode.VOICE` mode, and try to switch to `AudioPlaybackMode.MEDIA` mode as soon as you can after the voice call ends to allow other applications to play in media mode.

When you change audio play mode on iOS, mative apps playing music pause briefly.

The default value is `AudioPlaybackMode.MEDIA.`

Implementation
`public static function get audioPlaybackMode():String`
`public static function set audioPlaybackMode(value:String):void`
Throws

| `ArgumentError` — kInvalidParameterError

Related API Elements

flash.media.AudioPlaybackMode
flash.media.Sound

### bufferTime

property

`bufferTime:int`

Language Version: | ActionScript 3.0

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

The number of seconds to preload an embedded streaming sound into a buffer before it starts to stream. The data in a loaded sound, including its buffer time, cannot be accessed by a SWF file that is in a different domain unless you implement a cross-domain policy file. For more information about security and sound, see the Sound class description. The data in a loaded sound, including its buffer time, cannot be accessed by code in a file that is in a different domain unless you implement a cross-domain policy file. However, in the application sandbox in an AIR application, code can access data in sound files from any source. For more information about security and sound, see the Sound class description.

The `SoundMixer.bufferTime` property only affects the buffer time for embedded streaming sounds in a SWF and is independent of dynamically created Sound objects (that is, Sound objects created in ActionScript). The value of `SoundMixer.bufferTime` cannot override or set the default of the buffer time specified in the SoundLoaderContext object that is passed to the `Sound.load()` method.

Implementation
`public static function get bufferTime():int`
`public static function set bufferTime(value:int):void`

Related API Elements

Sound

### 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 that controls global sound properties. A SoundTransform object includes properties for setting volume, panning, left speaker assignment, and right speaker assignment. The SoundTransform object used in this property provides final sound settings that are applied to all sounds after any individual sound settings are applied.

Implementation
`public static function get soundTransform():flash.media:SoundTransform`
`public static function set soundTransform(value:flash.media:SoundTransform):void`

Related API Elements

SoundTransform

### useSpeakerphoneForVoice

property

`useSpeakerphoneForVoice:Boolean`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 3

Toggles the speakerphone when the device is in voice mode. By default, smartphones use the phone earpiece for audio output when `SoundMixer.audioPlaybackMode` is set to `AudioPlaybackMode.VOICE`. The `useSpeakerphoneForVoice` property lets you override the default output so that you can implement a speakerphone button in a phone application. This property has no effect in modes other than `AudioPlaybackMode.VOICE`. In desktop and TV environments, this property has no effect.

Note On iOS, if your application has set `audioPlaybackMode=VOICE` and another application is also playing in voice mode, you cannot set `useSpeakerphoneForVoice=true`.

Note On Android, you must set the `android.permission.MODIFY_AUDIO_SETTINGS` in the AIR application descriptor or changing this value has no effect. In addition, the setting is global device setting. Other applications running on the device can change the underlying device setting at any time.

The default value is `false.`

Implementation
`public static function get useSpeakerphoneForVoice():Boolean`
`public static function set useSpeakerphoneForVoice(value:Boolean):void`

Related API Elements

flash.media.AudioPlaybackMode
Method Detail

### areSoundsInaccessible

()
method

`public static function areSoundsInaccessible():Boolean`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9

Determines whether any sounds are not accessible due to security restrictions. For example, a sound loaded from a domain other than that of the content calling this method is not accessible if the server for the sound has no URL policy file that grants access to the domain of that domain. The sound can still be loaded and played, but low-level operations, such as getting ID3 metadata for the sound, cannot be performed on inaccessible sounds.

For AIR application content in the application security sandbox, calling this method always returns `false`. All sounds, including those loaded from other domains, are accessible to content in the application security sandbox.

Returns

| `Boolean` — The string representation of the boolean.

Related API Elements

computeSpectrum()

### computeSpectrum

()
method

`public static function computeSpectrum(outputArray:ByteArray, FFTMode:Boolean = false, stretchFactor:int = 0):void`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9

Takes a snapshot of the current sound wave and places it into the specified ByteArray object. The values are formatted as normalized floating-point values, in the range -1.0 to 1.0. The ByteArray object passed to the `outputArray` parameter is overwritten with the new values. The size of the ByteArray object created is fixed to 512 floating-point values, where the first 256 values represent the left channel, and the second 256 values represent the right channel.

Note: This method is subject to local file security restrictions and restrictions on cross-domain loading. If you are working with local files or sounds loaded from a server in a different domain than the calling content, you might need to address sandbox restrictions through a cross-domain policy file. For more information, see the Sound class description. In addition, this method cannot be used to extract data from RTMP streams, even when it is called by content that reside in the same domain as the RTMP server.

This method is supported over RTMP in Flash Player 9.0.115.0 and later and in Adobe AIR. You can control access to streams on Flash Media Server in a server-side script. For more information, see the `Client.audioSampleAccess` and `Client.videoSampleAccess` properties in Server-Side ActionScript Language Reference for Adobe Flash Media Server.

Parameters

| `outputArray:ByteArray` — A ByteArray object that holds the values associated with the sound. If any sounds are not available due to security restrictions (`areSoundsInaccessible == true`), the `outputArray` object is left unchanged. If all sounds are stopped, the `outputArray` object is filled with zeros.
| `FFTMode:Boolean` (default = `false`)`` — A Boolean value indicating whether a Fourier transformation is performed on the sound data first. Setting this parameter to `true` causes the method to return a frequency spectrum instead of the raw sound wave. In the frequency spectrum, low frequencies are represented on the left and high frequencies are on the right.
| `stretchFactor:int` (default = `0`)`` — The resolution of the sound samples. If you set the `stretchFactor` value to 0, data is sampled at 44.1 KHz; with a value of 1, data is sampled at 22.05 KHz; with a value of 2, data is sampled 11.025 KHz; and so on.

Related API Elements

areSoundsInaccessible()
flash.utils.ByteArray
flash.media.Sound
flash.media.SoundLoaderContext.checkPolicyFile
Example ( How to use this example )
In the following example, the `computeSpectrum()` method is used to produce a graphic representation of the sound wave data.

In the constructor, a sound file is loaded and set to play. (There is no error handling in this example and it is assumed that the sound file is in the same directory as the SWF file.) The example listens for the `Event.ENTER_FRAME` event while the sound plays, repeatedly triggering the `onEnterFrame()` method to draw a graph of the sound data values. When the sound finishes playing the `onPlaybackComplete()` method stops the drawing process by removing the listener for the `Event.ENTER_FRAME` event.

In the `onEnterFrame()` method, the `computeSpectrum()` method stores the raw sound in the `bytes` byte array object. The data is sampled at 44.1 KHz. The byte array containing 512 bytes of data, each of which contains a floating-point value between -1 and 1. The first 256 values represent the left channel, and the second 256 values represent the right channel. The first for loop, reads the first 256 data values (the left stereo channel) and draws a line from each point to the next using the `Graphics.lineTo()` method. (The vector graphic display of the sound wave is written directly on to the class's sprite object.) The sound bytes are read as 32-bit floating-point number from the byte stream and multiplied by the plot height to allow for the vertical range of the graph. The width is set to twice the width of the channel length. The second for loop reads the next set of 256 values (the right stereo channel), and plots the lines in reverse order. The `g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);` and `g.lineTo(0, PLOT_HEIGHT);` methods draw the baseline for the waves. The resulting waveform plot produces a mirror-image effect.

Copy

    package {
        import flash.display.Sprite;
        import flash.display.Graphics;
        import flash.events.Event;
        import flash.media.Sound;
        import flash.media.SoundChannel;
        import flash.media.SoundMixer;
        import flash.net.URLRequest;
        import flash.utils.ByteArray;
        import flash.text.TextField;

        public class SoundMixer_computeSpectrumExample extends Sprite {

            public function SoundMixer_computeSpectrumExample() {
                var snd:Sound = new Sound();
                var req:URLRequest = new URLRequest("Song1.mp3");
                snd.load(req);

                var channel:SoundChannel;
                channel = snd.play();
                addEventListener(Event.ENTER_FRAME, onEnterFrame);
                channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
            }

            private function onEnterFrame(event:Event):void {
                var bytes:ByteArray = new ByteArray();
                const PLOT_HEIGHT:int = 200;
                const CHANNEL_LENGTH:int = 256;

                SoundMixer.computeSpectrum(bytes, false, 0);

                var g:Graphics = this.graphics;

                g.clear();

                g.lineStyle(0, 0x6600CC);
                g.beginFill(0x6600CC);
                g.moveTo(0, PLOT_HEIGHT);

                var n:Number = 0;

                for (var i:int = 0; i < CHANNEL_LENGTH; i++) {
                    n = (bytes.readFloat() * PLOT_HEIGHT);
                    g.lineTo(i * 2, PLOT_HEIGHT - n);
                }

                g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);
                g.endFill();

                g.lineStyle(0, 0xCC0066);
                g.beginFill(0xCC0066, 0.5);
                g.moveTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);

                for (i = CHANNEL_LENGTH; i > 0; i--) {
                    n = (bytes.readFloat() * PLOT_HEIGHT);
                    g.lineTo(i * 2, PLOT_HEIGHT - n);
                }

                g.lineTo(0, PLOT_HEIGHT);
                g.endFill();
            }

            private function onPlaybackComplete(event:Event):void {
                removeEventListener(Event.ENTER_FRAME, onEnterFrame);
            }
        }
    }

### stopAll

()
method

`public static function stopAll():void`

Language Version: | ActionScript 3.0

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

Stops all sounds currently playing.

>In Flash Professional, this method does not stop the playhead. Sounds set to stream will resume playing as the playhead moves over the frames in which they are located.

When using this property, consider the following security model:

- By default, calling the `SoundMixer.stopAll()` method stops only sounds in the same security sandbox as the object that is calling the method. Any sounds whose playback was not started from the same sandbox as the calling object are not stopped.
- When you load the sound, using the `load()` method of the Sound class, you can specify a `context` parameter, which is a SoundLoaderContext object. If you set the `checkPolicyFile` property of the SoundLoaderContext object to `true`, Flash Player or Adobe AIR checks for a cross-domain policy file on the server from which the sound is loaded. If the server has a cross-domain policy file, and the file permits the domain of the calling content, then the file can stop the loaded sound by using the `SoundMixer.stopAll()` method; otherwise it cannot.

However, in Adobe AIR, content in the `application` security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: Security.

Example ( How to use this example )
In the following example, the `stopAll()` method is used to mute two sounds that are playing at the same time.

In the constructor, two different sound files are loaded and set to play. The first sound is loaded locally and is assigned to a sound channel. (It is assumed that the file is in the same directory as the SWF file.) The second file is loaded and streamed from the Adobe site. In order to use the `SoundMixer.stopAll()` method, all sound must be accessible. (A SoundLoaderContext object can be used to check for the cross-domain policy file.) Each sound also has an event listener that is invoked if an IO error occurred while loading the sound file. A `muteButton` text field is also created. It listens for a click event, which will invoke the `muteButtonClickHandler()` method.

In the `muteButtonClickHandler()` method, if the text field content is "MUTE," the `areSoundsInaccessible()` method checks if the sound mixer has access to the files. If the files are accessible, the `stopAll()` method stops the sounds. By selecting the text field again, the first sound begins playing and the text field's content changes to "MUTE" again. This time, the `stopAll()` method mutes the one sound that is running. Note that sound channel `stop()` method can also be used to stop a specific sound assigned to the channel. (To use the channel functionally, the sound needs to be reassigned to the channel each time the `play()` method is invoked.)

Copy

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

        public class SoundMixer_stopAllExample extends Sprite  {
            private var firstSound:Sound = new Sound();
            private var secondSound:Sound = new Sound();
            private var muteButton:TextField = new TextField();
            private var channel1:SoundChannel = new SoundChannel();

            public function SoundMixer_stopAllExample() {
                firstSound.load(new URLRequest("mySound.mp3"));
                secondSound.load(new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3"));

                firstSound.addEventListener(IOErrorEvent.IO_ERROR, firstSoundErrorHandler);
                secondSound.addEventListener(IOErrorEvent.IO_ERROR, secondSoundErrorHandler);

                channel1 = firstSound.play();
                secondSound.play();

                muteButton.autoSize = TextFieldAutoSize.LEFT;
                muteButton.border = true;
                muteButton.background = true;
                muteButton.text = "MUTE";

                muteButton.addEventListener(MouseEvent.CLICK, muteButtonClickHandler);

                this.addChild(muteButton);
            }

            private function muteButtonClickHandler(event:MouseEvent):void {

                if(muteButton.text == "MUTE") {

                    if(SoundMixer.areSoundsInaccessible() == false) {
                        SoundMixer.stopAll();
                        muteButton.text = "click to play only one of sound.";
                    }
                    else {
                        muteButton.text = "The sounds are not accessible.";
                    }
                }
               else {
                    firstSound.play();
                    muteButton.text = "MUTE";
               }
            }

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

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

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