class in UnityEngine
/
Inherits from:Behaviour
/
Implemented in:UnityEngine.AudioModule
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.
CloseFor 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.
CloseA 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.
Additional resources: 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; } } }
bypassEffects | Bypass effects (Applied from filter components or global listener filters). |
bypassListenerEffects | When set, global effects on the AudioListener doesn't apply to the audio signal generated by the AudioSource. It also does'nt apply, if the AudioSource is playing into a mixer group. |
bypassReverbZones | When set, it doesn't route the signal from an AudioSource into the global reverb associated with reverb zones. |
clip | The default AudioClip to play. |
dopplerLevel | Sets the Doppler scale for this AudioSource. |
gamepadSpeakerOutputType | Gets or sets the gamepad audio output type for this audio source. |
ignoreListenerPause | Allows 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. |
ignoreListenerVolume | This makes the audio source not take into account the volume of the audio listener. |
isPlaying | Returns whether the AudioSource is currently playing an AudioResource(Read Only). |
isVirtual | True if all sounds played by the AudioSource, such as main sound started by Play() or playOnAwake, and one-shots are culled by the audio system. |
loop | Checks if the audio clip is looping |
maxDistance | (Logarithmic rolloff) MaxDistance is the distance a sound stops attenuating at. |
minDistance | Within the Min distance the AudioSource will cease to grow louder in volume. |
mute | Un- / Mutes the AudioSource. Mute sets the volume=0, Un-Mute restore the original volume. |
outputAudioMixerGroup | The target group to which the AudioSource should route its signal. |
panStereo | Pans a playing sound in a stereo way (left or right). This only applies to sounds that are Mono or Stereo. |
pitch | The pitch of the audio source. |
playOnAwake | If set to true, the audio source will automatically start playing on awake. |
priority | Sets the priority of the AudioSource. |
resource | The default AudioResource to play. |
reverbZoneMix | The amount by which the signal from the AudioSource will be mixed into the global reverb associated with the Reverb Zones. |
rolloffMode | Sets/Gets how the AudioSource attenuates over distance. |
spatialBlend | Sets 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. |
spatialize | Enables or disables spatialization. |
spatializePostEffects | Determines if the spatializer effect is inserted before or after the effect filters. |
spread | Sets the spread angle (in degrees) of a 3d stereo or multichannel sound in speaker space. |
time | Playback position in seconds. |
timeSamples | Playback position in PCM samples. |
velocityUpdateMode | Whether the Audio Source should be updated in the fixed or dynamic update. |
volume | The volume of the audio source (0.0 to 1.0). |
DisableGamepadOutput | Disables audio output to a gamepad for this audio source. |
GetAmbisonicDecoderFloat | Reads a user-defined parameter of a custom ambisonic decoder effect that is attached to an AudioSource. |
GetCustomCurve | Get the current custom curve for the given AudioSourceCurveType. |
GetOutputData | Provides a block of the currently playing source's output data. |
GetSpatializerFloat | Reads a user-defined parameter of a custom spatializer effect that is attached to an AudioSource. |
GetSpectrumData | Provides the block of audio frequencies (spectrum data) of the AudioSource that is currently playing. |
Pause | Pauses playing the clip. |
Play | Plays the clip. |
PlayDelayed | Plays 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. |
PlayOneShot | Plays an AudioClip, and scales the AudioSource volume by volumeScale. |
PlayOnGamepad | Enable playing of audio source though a specfic gamepad. |
PlayScheduled | Plays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads from. |
SetAmbisonicDecoderFloat | Sets a user-defined parameter of a custom ambisonic decoder effect that is attached to an AudioSource. |
SetCustomCurve | Set the custom curve for the given AudioSourceCurveType. |
SetScheduledEndTime | Changes 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. |
SetScheduledStartTime | Changes the time at which a sound that has already been scheduled to play will start. |
SetSpatializerFloat | Sets a user-defined parameter of a custom spatializer effect that is attached to an AudioSource. |
Stop | Stops playing the clip. |
UnPause | Unpause the paused playback of this AudioSource. |
GamepadSpeakerSupportsOutputType | Check if the platform supports an audio output type on gamepads. |
PlayClipAtPoint | Plays an AudioClip at a given position in world space. |
enabled | Enabled Behaviours are Updated, disabled Behaviours are not. |
isActiveAndEnabled | Reports whether a GameObject and its associated Behaviour is active and enabled. |
gameObject | The game object this component is attached to. A component is always attached to a game object. |
tag | The tag of this game object. |
transform | The Transform attached to this GameObject. |
hideFlags | Should the object be hidden, saved with the Scene or modifiable by the user? |
name | The name of the object. |
BroadcastMessage | Calls the method named methodName on every MonoBehaviour in this game object or any of its children. |
CompareTag | Checks the GameObject's tag against the defined tag. |
GetComponent | Gets a reference to a component of type T on the same GameObject as the component specified. |
GetComponentInChildren | Gets a reference to a component of type T on the same GameObject as the component specified, or any child of the GameObject. |
GetComponentIndex | Gets the index of the component on its parent GameObject. |
GetComponentInParent | Gets a reference to a component of type T on the same GameObject as the component specified, or any parent of the GameObject. |
GetComponents | Gets references to all components of type T on the same GameObject as the component specified. |
GetComponentsInChildren | Gets references to all components of type T on the same GameObject as the component specified, and any child of the GameObject. |
GetComponentsInParent | Gets references to all components of type T on the same GameObject as the component specified, and any parent of the GameObject. |
SendMessage | Calls the method named methodName on every MonoBehaviour in this game object. |
SendMessageUpwards | Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour. |
TryGetComponent | Gets the component of the specified type, if it exists. |
GetInstanceID | Gets the instance ID of the object. |
ToString | Returns the name of the object. |
Destroy | Removes a GameObject, component or asset. |
DestroyImmediate | Destroys the object obj immediately. You are strongly recommended to use Destroy instead. |
DontDestroyOnLoad | Do not destroy the target Object when loading a new Scene. |
FindAnyObjectByType | Retrieves any active loaded object of Type type. |
FindFirstObjectByType | Retrieves the first active loaded object of Type type. |
FindObjectsByType | Retrieves a list of all loaded objects of Type type. |
Instantiate | Clones the object original and returns the clone. |
InstantiateAsync | Captures a snapshot of the original object (that must be related to some GameObject) and returns the AsyncInstantiateOperation. |
bool | Does 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. |
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.
When you visit any website, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and change our default settings. However, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
More information
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
These cookies may be set through our site by our advertising partners. They may be used by those companies to build a profile of your interests and show you relevant adverts on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device. If you do not allow these cookies, you will experience less targeted advertising. Some 3rd party video providers do not allow video views without targeting cookies. If you are experiencing difficulty viewing a video, you will need to set your cookie preferences for targeting to yes if you wish to view videos from these providers. Unity does not control this.
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.