Audio

Объект АУДИО позволяет добавлять и проигрывать в проект аудио ресурсы, управлять воспроизведением, а также изменять громкость и выбирать аудиофайл.

Работа с объектом Аудио

Object AUDIO properties

../_images/audio1.png
Parameter Description Note
Ресурс аудио (audioResource) Allows to select an audio file of the required format.

Upon creating an object AUDIO, the audio resource is not defined.

In order to add an audio resource, one needs to select one of the pre-uploaded audio resources from the list or select “Add a new one”, in case you want to use audios that have not yet been added to the project resources.

Громкость (volume) Allows to set the volume of the audio resource.

Maximum values for the parameter:

1.000 - corresponds to sound volume set to 100%.

Панорамирование (pan) Распределение звуковой волны в пространственном диапазоне звукового поля или, иначе говоря, распределение звука по стереоканалам (влево, вправо, центр).

By default, the value of this parameter is set to 0.000, that is, the sound is equally distributed between the stereo channels.

To “shift” the sound to the left or to the right, the value of this parameter should be changed.

Минимальное и максимальное значения для параметра:

-1.000 - sound is fully shifted to the left

1.000 - the sound is fully shifted to the right

Режим воспроизведения (playMode) Allows to select the playback mode of the audio resource. Possible values of the parameter when choosing the playback mode: once or repeat.
Декодирование на ходу (liveDecoding) When this option is selected, the audio file is decoded and sent to RAM for playback in batches.  

Note

Decoding is the process of restoring the original form of presenting the information.

An audio file that is added to a project is initially encoded and consists of data packets. Before it is played, it will be decoded and fully loaded into RAM. However the decoded file weighs several times more than the encoded one which means that a 1MB audio file will take memory is much more space than 1 MB after decoding. This can be crucial when audio of large sizes (such as .flac) are used in the project.

However, it is possible to make decoding and sending to RAM for playing the file in batches. Thanks to the Live decoding feature it is possible to reduce the use of RAM and not fill it up with large audio files.

NOTE: remember that by freeing up RAM this way, the CPU is loaded by live decoding processes. In this case it is important to prioritize and decide what is of more importance: to free up RAM or not to load the CPU .

параметр Ресурс аудио; audioResource

The parameter allows to select an audio resource for a chosen object.

Note

Можно присвоить как ресурс, так и id ресурса. Подробнее см. Ресурсы.

параметр Громкость; volume

Allows to set the volume of the audio resource. The maximum volume corresponds to the value 1, silent playback - value 0. The default value is 1. See the Установить громкость (setVolume) action for details.

параметр Панорамирование; pan

Параметр устанавливает распределение звука между стерео-каналами.

-1.000 - звук полностью смещен влево, 1.000 - звук полностью смещен вправо. По умолчанию равен 0.000.

параметр Режим воспроизведения; playMode

Параметр имеет два значения: “один раз” и “повтор”. По умолчанию выставлено значение “один раз”. Подробнее, см. действие Установить режим проигрывания (setPlayMode)

параметр Декодирование на ходу; liveDecoding

Параметр позволяет установить декодирование “на ходу”. При выборе данного параметра декодирование и отправка в оперативную память аудио файла для воспроизведения производится пакетами, что позволяет значительно уменьшить ее расход.

Действия объекта Аудио

../_images/audio3.png
Action Description
Установить аудиоресурс (setAudioResource) Allows to set a new audio resource for playback.
Установить громкость (setVolume) Позволяет установить громкость воспроизведения, отличную от той, которая установлена в свойствах объектах Аудио.
Установить панорамирование (setPan) Allows to change the distribution of the sound wave in the spatial range of the sound field, or, in other words, the distribution of sound on stereo channels (left, right, center).
Установить режим проигрывания (setPlayMode) Allows to set a new audio resource playback mode: once or loop.
действие Установить аудио ресурс; setAudioResource(resource)

Set a new audio resource (parameter Ресурс аудио (audioResource)).

Parameters:Ресурс аудио / audioResource – The new audio resource to be exposed to the object.

This call is equivalent to assigning the parameter Ресурс аудио (audioResource)

действие Установить громкость; setVolume(volume)

Установить новую громкость проигрывания аудио ресурса, отличную от той, которая установлена в свойствах объектах Аудио (параметр Громкость (volume)).

Parameters:громкость / volume – New volume level.
действие Установить панорамирование; setPan(pan)

Установить значение панорамирования. Подробнее см. Панорамирование (pan)

действие Установить режим проигрывания; setPlayMode(mode)

Установить новый режим проигрывания аудио ресурса: один раз или повтор (параметр Режим воспроизведения (playMode)).

Parameters:Режим проигрывания / playMode – Новый режим проигрывания: *Один раз*(AudioReactor.PlayMode.ONCE) или *Повтор*(AudioReactor.PlayMode.LOOP).

Events and actions of the object AUDIO (playback control)

Inserted into AudioReactor

../_images/audio2.png
Event Description
Запущен (onStart)

Вызывается при запуске проигрывания аудио ресурса с самого начала.

Например, вам необходимо вместе с аудио запустить анимацию у модели – это событие поможет создать такую логику работы.

Остановлен (onStop)

Called when a user stops playing an audio resource.

Например, если в выбранный момент вам необходимо сделать так, чтобы при остановке аудио пользователем поменялось какое-либо изображение – это событие поможет создать такую логику работы.

Приостановлен (onPause)

Called when audio is paused.

For example, to stop an animation of the model when the audio is paused, this event will help to create this logic.

Возобновлён (onResume)

Called when the audio is unpaused.

For example, to resume the animation of the model when the audio is unpaused - this event will help to create this logic.

Завершён (onFinished)

Called when the audio has finished playing.

Например, если вам необходимо сделать в проекте так, чтобы по завершении проигрывания композиции появлялась надпись “конец”, то это событие поможет создать такую логику работы.

Action Description
Проиграть (play)

Allows to start playing the installed audio resource.

Audio always starts from the beginning

Остановить (stop) Allows to stop playback and rewind the installed audio resource to the beginning.
Приостановить (pause) Allows to pause the playback of the installed audio resource (pause playback).
Возобновить (resume) Позволяет возобновить воспроизведение установленного аудио ресурса с того места, где он был приостановлен (снять паузу).
событие Запущен; onStart

Вызывается при запуске проигрывания аудио ресурса с самого начала. При вызове действия Возобновить (resume) данное событие не вызывается. Подробнее, см. действие Проиграть (play).

событие Остановлен; onStop

Called when the user stops playing an audio resource. This event is fired only when the Остановить (stop) action is called while the audio is playing.

событие Приостановлен; onPause

Called when the audio is paused. This event is fired only when the Приостановить (pause) action is called while the audio is playing.

событие Возобновлён; onResume

Called when the audio is unpaused. This event is fired only when the Возобновить (resume) action is called on paused audio.

событие Завершён; onFinished

Called when the audio resource finishes playing. When the Остановить (stop) action is called, this event is not fired.

действие Проиграть; play(playMode = AudioReactor.PlayMode.ONCE)

Start playing the audio resource from the beginning, regardless of the current state of the audio. When called, the Запущен (onStart) event comes.

Если Режим проигрывания / playMode выставлен как Один раз / AudioReactor.PlayMode.ONCE, то после окончания проигрывания будет вызвано событие Завершён (onFinished). Если режим проигрывания выставлен как Повтор / AudioReactor.PlayMode.LOOP, то проигрывание никогда не закончится само, и, соответственно, событие вызвано не будет. Однако режим проигрывания может быть изменён явно при помощи действия Установить режим проигрывания (setPlayMode).

Parameters:Режим / playMode – Режим проигрывания: AudioReactor.PlayMode.ONCE - проиграть один раз, AudioReactor.PlayMode.LOOP - проигрывать в цикле.

If the Studio is set to Do not change, the mode specified in the object’s parameters will be set.

Note

Вызов с playMode равным nil(если параметр не указан или nil указан явно) начнет воспроизведение с режимом проигрывания AudioReactor.PlayMode.ONCE или установленным до вызова вручную.

действие Остановить; stop()

Stop playback and rewind the audio to the beginning. If the audio has not been started and is in its initial state, the action will not work. On a successful call, the Остановлен (onStop) event comes.

действие Приостановить ; pause()

Pause audio playback. If the audio has not been started and is in its initial state, the action will not work. On a successful call, the Приостановлен (onPause) event comes.

Note

Даже если аудио уже стоит на паузе, повторный вызов действия Приостановить (pause) приведет к вызову события Приостановлен (onPause).

действие Возобновить ; resume()

Continue playing the audio resource from where it was paused. If the audio has not been started and is in its initial state, the action will not work. On successful call, the Возобновлён (onResume) event comes.

Note

Even if audio is currently playing, calling the Возобновлён (onResume) action will cause the Возобновлён (onResume) event to be fired.

Advanced

Вспомогательные методы Description
isPlaying()

Возвращает true, если аудио ресурс проигрывается в текущий момент и false в обратном случае. Пример кода

local audio = reactorController:getReactorByName("Audio")

if audio:isPlaying() then
  doSomething()
end