Version: 2022.1
LanguageEnglish
  • C#

AudioSource

class in UnityEngine

/

Inherits from:Behaviour

/

Implemented in:UnityEngine.AudioModule

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Switch to Manual

Description

A representation of audio sources in 3D.

An AudioSource is attached to a GameObject for playing back sounds in a 3D environment. In order to play 3D sounds you also need to have a AudioListener. The audio listener is normally attached to the camera you want to use. Whether sounds are played in 3D or 2D is determined by AudioImporter settings.

You can play a single audio clip using Play, Pause and Stop. You can also adjust its volume while playing using the volume property, or seek using time. Multiple sounds can be played on one AudioSource using PlayOneShot. You can play a clip at a static position in 3D space using PlayClipAtPoint.

See Also: AudioListener, AudioClip, AudioSource component.

//This script allows you to toggle music to play and stop.
//Assign an AudioSource to a GameObject and attach an Audio Clip in the Audio Source. Attach this script to the GameObject.

using UnityEngine;

public class Example : MonoBehaviour { AudioSource m_MyAudioSource;

//Play the music bool m_Play; //Detect when you use the toggle, ensures music isn’t played multiple times bool m_ToggleChange;

void Start() { //Fetch the AudioSource from the GameObject m_MyAudioSource = GetComponent<AudioSource>(); //Ensure the toggle is set to true for the music to play at start-up m_Play = true; }

void Update() { //Check to see if you just set the toggle to positive if (m_Play == true && m_ToggleChange == true) { //Play the audio you attach to the AudioSource component m_MyAudioSource.Play(); //Ensure audio doesn’t play more than once m_ToggleChange = false; } //Check if you just set the toggle to false if (m_Play == false && m_ToggleChange == true) { //Stop the audio m_MyAudioSource.Stop(); //Ensure audio doesn’t play more than once m_ToggleChange = false; } }

void OnGUI() { //Switch this toggle to activate and deactivate the parent GameObject m_Play = GUI.Toggle(new Rect(10, 10, 100, 30), m_Play, "Play Music");

//Detect if there is a change with the toggle if (GUI.changed) { //Change to true to show that there was just a change in the toggle state m_ToggleChange = true; } } }

Properties

bypassEffectsBypass effects (Applied from filter components or global listener filters).
bypassListenerEffectsWhen set global effects on the AudioListener will not be applied to the audio signal generated by the AudioSource. Does not apply if the AudioSource is playing into a mixer group.
bypassReverbZonesWhen set doesn't route the signal from an AudioSource into the global reverb associated with reverb zones.
clipThe default AudioClip to play.
dopplerLevelSets the Doppler scale for this AudioSource.
gamepadSpeakerOutputTypeGets or sets the gamepad audio output type for this audio source.
ignoreListenerPauseAllows AudioSource to play even though AudioListener.pause is set to true. This is useful for the menu element sounds or background music in pause menus.
ignoreListenerVolumeThis makes the audio source not take into account the volume of the audio listener.
isPlayingIs the clip playing right now (Read Only)?
isVirtualTrue if all sounds played by the AudioSource (main sound started by Play() or playOnAwake as well as one-shots) are culled by the audio system.
loopIs the audio clip looping?
maxDistance(Logarithmic rolloff) MaxDistance is the distance a sound stops attenuating at.
minDistanceWithin the Min distance the AudioSource will cease to grow louder in volume.
muteUn- / Mutes the AudioSource. Mute sets the volume=0, Un-Mute restore the original volume.
outputAudioMixerGroupThe target group to which the AudioSource should route its signal.
panStereoPans a playing sound in a stereo way (left or right). This only applies to sounds that are Mono or Stereo.
pitchThe pitch of the audio source.
playOnAwakeIf set to true, the audio source will automatically start playing on awake.
prioritySets the priority of the AudioSource.
reverbZoneMixThe amount by which the signal from the AudioSource will be mixed into the global reverb associated with the Reverb Zones.
rolloffModeSets/Gets how the AudioSource attenuates over distance.
spatialBlendSets how much this AudioSource is affected by 3D spatialisation calculations (attenuation, doppler etc). 0.0 makes the sound full 2D, 1.0 makes it full 3D.
spatializeEnables or disables spatialization.
spatializePostEffectsDetermines if the spatializer effect is inserted before or after the effect filters.
spreadSets the spread angle (in degrees) of a 3d stereo or multichannel sound in speaker space.
timePlayback position in seconds.
timeSamplesPlayback position in PCM samples.
velocityUpdateModeWhether the Audio Source should be updated in the fixed or dynamic update.
volumeThe volume of the audio source (0.0 to 1.0).

Public Methods

DisableGamepadOutputDisables audio output to a gamepad for this audio source.
GetAmbisonicDecoderFloatReads a user-defined parameter of a custom ambisonic decoder effect that is attached to an AudioSource.
GetCustomCurveGet the current custom curve for the given AudioSourceCurveType.
GetOutputDataProvides a block of the currently playing source's output data.
GetSpatializerFloatReads a user-defined parameter of a custom spatializer effect that is attached to an AudioSource.
GetSpectrumDataProvides a block of the currently playing audio source's spectrum data.
PausePauses playing the clip.
PlayPlays the clip.
PlayDelayedPlays the clip with a delay specified in seconds. Users are advised to use this function instead of the old Play(delay) function that took a delay specified in samples relative to a reference rate of 44.1 kHz as an argument.
PlayOneShotPlays an AudioClip, and scales the AudioSource volume by volumeScale.
PlayOnGamepadEnable playing of audio source though a specfic gamepad.
PlayScheduledPlays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads from.
SetAmbisonicDecoderFloatSets a user-defined parameter of a custom ambisonic decoder effect that is attached to an AudioSource.
SetCustomCurveSet the custom curve for the given AudioSourceCurveType.
SetScheduledEndTimeChanges the time at which a sound that has already been scheduled to play will end. Notice that depending on the timing not all rescheduling requests can be fulfilled.
SetScheduledStartTimeChanges the time at which a sound that has already been scheduled to play will start.
SetSpatializerFloatSets a user-defined parameter of a custom spatializer effect that is attached to an AudioSource.
StopStops playing the clip.
UnPauseUnpause the paused playback of this AudioSource.

Static Methods

GamepadSpeakerSupportsOutputTypeCheck if the platform supports an audio output type on gamepads.
PlayClipAtPointPlays an AudioClip at a given position in world space.

Inherited Members

Properties

enabledEnabled Behaviours are Updated, disabled Behaviours are not.
isActiveAndEnabledReports whether a GameObject and its associated Behaviour is active and enabled.
gameObjectThe game object this component is attached to. A component is always attached to a game object.
tagThe tag of this game object.
transformThe Transform attached to this GameObject.
hideFlagsShould the object be hidden, saved with the Scene or modifiable by the user?
nameThe name of the object.

Public Methods

BroadcastMessageCalls the method named methodName on every MonoBehaviour in this game object or any of its children.
CompareTagChecks the GameObject's tag against the defined tag.
GetComponentReturns the component of type if the GameObject has one attached.
GetComponentInChildrenReturns the Component of type in the GameObject or any of its children using depth first search.
GetComponentInParentReturns the Component of type in the GameObject or any of its parents.
GetComponentsReturns all components of Type type in the GameObject.
GetComponentsInChildrenReturns all components of Type type in the GameObject or any of its children. Works recursively.
GetComponentsInParentReturns all components of Type type in the GameObject or any of its parents.
SendMessageCalls the method named methodName on every MonoBehaviour in this game object.
SendMessageUpwardsCalls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.
TryGetComponentGets the component of the specified type, if it exists.
GetInstanceIDGets the instance ID of the object.
ToStringReturns the name of the object.

Static Methods

DestroyRemoves a GameObject, component or asset.
DestroyImmediateDestroys the object obj immediately. You are strongly recommended to use Destroy instead.
DontDestroyOnLoadDo not destroy the target Object when loading a new Scene.
FindObjectOfTypeReturns the first active loaded object of Type type.
FindObjectsOfTypeGets a list of all loaded objects of Type type.
InstantiateClones the object original and returns the clone.

Operators

boolDoes the object exist?
operator !=Compares if two objects refer to a different object.
operator ==Compares two object references to see if they refer to the same object.