AudioSource

class in UnityEngine

/

Inherits from:Behaviour

Switch to Manual

Description

Представление источников звука в 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 &amp;&amp; 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 &amp;&amp; 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; } } }

Variables

bypassEffectsБайпас эффекты (Наложенные на компоненты фильтров или фильтры глобальных слушателей).
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.
clipВыбранный по умолчанию AudioClip для проигрывания.
dopplerLevelУстанавливает коэффициент Доплера для выбранного источника звука AudioSorce.
gamepadSpeakerOutputTypeGets or sets the gamepad audio output type for this audio source.
ignoreListenerPauseПозволяет источнику звука AudioSource продолжать проигрывание звука, даже если значение AudioListener.pause установлено true. Это может быть полезным для звуков элементов меню или фоновой музыки в меню паузы.
ignoreListenerVolumeЭто позволяет источнику аудио не принимать во внимание громкость слушателя звуков.
isPlayingИграет ли в данный момент clip (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.
loopАудио клип зациклен?
maxDistance(Логарифмическое затухание) MaxDistance это дистанция, на которой звук перестаёт ослабевать.
minDistanceВ пределах Min distance источник звука AudioSource прекратит увеличение громкости.
muteВключает/выключает звук источника звука AudioSource. Выключение делает громкость = 0. Включение возвращает оригинальную громкость.
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.
pitchВысота звука источника звука.
playOnAwakeЕсли установлено в значение true, источник звука автоматически начнёт проигрывание при пробуждении (awake).
priorityУстанавливает приоритет для AudioSource.
reverbZoneMixThe amount by which the signal from the AudioSource will be mixed into the global reverb associated with the Reverb Zones.
rolloffModeУстанавливает/Возвращает для источника звука AudioSource способ затухания с расстоянием.
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.
spreadУстанавливает для угла раскрытия режим 3d стерео или мультиканальный звук в пространстве динамиков.
timeПозиция воспроизведения, в секундах.
timeSamplesПозиция воспроизведения в PCM сэмпле.
velocityUpdateModeДолжен ли источник звука обновляться в фиксированном (fixed) или динамическом (dynamic) update.
volumeГромкость источника звука (от 0.0 до 1.0).

Public Functions

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.
GetCustomCurveУстанавливает коэффициент Доплера для выбранного источника звука AudioSorce.
GetOutputDataВозвращает блок из выходных данных текущего играющего источника.
GetSpatializerFloatReads a user-defined parameter of a custom spatializer effect that is attached to an AudioSource.
GetSpectrumDataВозвращает блок из данных спектра из текущего играющего источника.
PauseПриостанавливает воспроизведение clip.
PlayPlays the clip.
PlayDelayedПроигрывает clip с задержкой, заданной в секундах. Рекомендуется использовать эту функцию вместо старой Play(delay) , которая в качестве аргумента использует задержку в сэмплах, соответствующих частоте сэмплирования (дискретизации) 44.1 кГц.
PlayOneShotПроигрывает AudioClip и масштабирует громкость AudioSource в соответствии с volumeScale.
PlayOnGamepadEnable playing of audio source though a specfic gamepad.
PlayScheduledПроигрывает clip в заданное время на абсолютной временной шкале, считанной из AudioSettings.dspTime .
SetAmbisonicDecoderFloatSets a user-defined parameter of a custom ambisonic decoder effect that is attached to an AudioSource.
SetCustomCurveУстанавливает коэффициент Доплера для выбранного источника звука AudioSorce.
SetScheduledEndTimeИзменяет время, в которое звук, уже запланированный на воспроизведение, закончит воспроизведение. Обратите внимание, что в зависимости от времени, не каждый запрос на перепланирование может быть выполнен.
SetScheduledStartTimeИзменяет время, в которое уже запланированный звук начнёт играть.
SetSpatializerFloatSets a user-defined parameter of a custom spatializer effect that is attached to an AudioSource.
StopОстанавливает воспроизведение clip.
UnPauseУстанавливает коэффициент Доплера для выбранного источника звука AudioSorce.

Static Functions

GamepadSpeakerSupportsOutputTypeCheck if the platform supports an audio output type on gamepads.
PlayClipAtPointПроигрывает AudioClip в заданной точке мирового пространства.

Inherited members

Variables

enabledВключенное Поведение обновляется, выключенное Поведение не обновляется.
isActiveAndEnabledHas the Behaviour had active and enabled called?
gameObjectИгровой объект к которому прикреплён данный компонент. Компонент всегда прикреплён к игровому объекту.
tagТег данного игрового объекта.
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 Functions

BroadcastMessageВызывает метод названный methodName на каждом MonoBehaviour этого game object-а или любого из его потомков.
CompareTagПомечен ли данный игровой объект тегом tag?
GetComponentReturns the component of Type type if the GameObject has one attached, null if it doesn't. Will also return disabled components.
GetComponentInChildrenВозвращает компонент типа type в GameObject или некоторого его потомка через поиск в глубину.
GetComponentInParentВозвращает все компоненты типа type из GameObject'а или из любого его родителя.
GetComponentsВозвращает все компоненты типа type в GameObject.
GetComponentsInChildrenВозвращает все компоненты типа type в GameObject или любому из его потомков.
GetComponentsInParentВозвращает все компоненты типа type в GameObject или любому из его родителей.
SendMessageВызывает метод с названием methodName в каждом MonoBehaviour в этом игровом объекте.
SendMessageUpwardsВызывает метод с именем methodName в каждом MonoBehaviour в этом игровом объекте и в каждом предке поведения.
TryGetComponentGets the component of the specified type, if it exists.
GetInstanceIDReturns the instance id of the object.
ToStringReturns the name of the object.

Static Functions

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.
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961