This page has been translated automatically.
Видеоуроки
Интерфейс
Основы
Продвинутый уровень
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Профессиональный уровень (SIM)
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Режимы вывода изображения
Физика
Браузер SDK 2
Лицензирование и типы лицензий
Дополнения (Add-Ons)
Демонстрационные проекты
API Samples
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Контроль версий
Настройки и предпочтения
Работа с проектами
Настройка параметров ноды
Setting Up Materials
Настройка свойств
Освещение
Sandworm
Использование инструментов редактора для конкретных задач
Расширение функционала редактора
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World-ноды
Звуковые объекты
Объекты поиска пути
Player-ноды
Программирование
Основы
Настройка среды разработки
C++
C#
UnigineScript
Унифицированный язык шейдеров UUSL (Unified UNIGINE Shader Language)
Плагины
Форматы файлов
Материалы и шейдеры
Rebuilding the Engine Tools
Интерфейс пользователя (GUI)
Двойная точность координат
API
Animations-Related Classes
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
VR-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Визуальный редактор материалов
Material Nodes Library
Miscellaneous
Input
Math
Matrix
Textures
Art Samples
Учебные материалы

Controlling Sound Sources Globally

In this example, you will learn how to stop and start the playback of all sounds on a specific channel.

Creating Sounds#

In order to control sounds in the scene, we should have them. Let's review how to add sounds.

The Sound Source object can be created in UnigineEditor as a node (let's assume we did this way in our example), while Ambient Source doesn't have any specific location and is created via code only.

In the Init() method, we create the ambient source and configure it as required.

Source code (C#)
private void Init()
{
	AmbientSource ambient0 = new AmbientSource("sound0.mp3");
		ambient0.SourceMask = 1;
		ambient0.Loop = 1;
		ambient0.Play();

}

Having all these sources at hand, we can fine-tune their behavior.

Getting Sounds#

Now we need to get sounds to control them. We'll get Sound Sources by using the method World.GetNodesByType() and add them to the vector storing all sound source nodes:

Source code (C#)
private void GetAllSoundSources(out List<SoundSource> sounds)
{
	List<Node> nodes = new List<Node>();
	World.GetNodesByType((int)Node.TYPE.SOUND_SOURCE, nodes);

	sounds = new List<SoundSource>();
	foreach (var n in nodes)
		sounds.Add(n as SoundSource);
}

We'll also declare a vector storing all ambient sounds:

Source code (C#)
private List<AmbientSource> ambientSounds = new List<AmbientSource>();

And add one more sound setting in the Init() method that will add the ambient sound to the vector:

Source code (C#)
ambientSounds.Add(ambient0);

Controlling the Playback#

We can control the playback via the SoundSource and the AmbientSource class methods Play(), Stop(), and the Time property. The general approach is to get all sound sources with the mask of the required channel enabled and then pause them using Stop(). This method doesn't reset the playback time, therefore the Play() method will resume the sound playback from the moment it has been paused.

First, we create a method that plays sounds that have the corresponding sound channel enabled.

Source code (C#)
private void PlaySourceChannel(int number, in List<SoundSource> sounds)
{
	foreach (var s in sounds)
	{
		if ((s.SourceMask & (1 << number)) != 0)
			s.Play();
	}
}

Then we create a method that will play both Sound Sources and Ambient Sources on the specified channel at the same time:

Source code (C#)
private void PlaySourceChannel(int number, in List<SoundSource> sources, in List<AmbientSource> ambients)
{
	PlaySourceChannel(number, sources);

	foreach (var a in ambients)
	{
		if ((a.SourceMask & (1 << number)) != 0)
			a.Play();
	}
}

Stopping the sound playback uses the same approach.

Notice
If a sound source plays on several channels, disabling it means that it will be disabled on all channels.
Source code (C#)
private void StopSourceChannel(int number, in List<SoundSource> sounds)
{
	foreach (var s in sounds)
	{
		if ((s.SourceMask & (1 << number)) != 0)
			s.Stop();
	}
}

private void StopSourceChannel(int number, in List<SoundSource> sources, in List<AmbientSource> ambients)
{
	StopSourceChannel(number, sources);

	foreach (var a in ambients)
	{
		if ((a.SourceMask & (1 << number)) != 0)
			a.Stop();
	}
}

The only thing left is to bind methods and buttons:

Source code (C#)
private void Update()
{
	if (Input.IsKeyDown(Input.KEY.P))
		{
			GetAllSoundSources(out List<SoundSource> sources);
			PlaySourceChannel(0, sources, ambientSounds);
		}

		if (Input.IsKeyDown(Input.KEY.S))
		{
			GetAllSoundSources(out List<SoundSource> sources);
			StopSourceChannel(0, sources, ambientSounds);
		}
}

Code Sample#

Here's a complete code:

You can create a C# component and add the following code to it except for the PropertyGuid value, which is generated individually for each component at its creation. Keep in mind adding audio files with the corresponding names to your project.

Source code (C#)
using System;
using System.Collections;
using System.Collections.Generic;
using Unigine;

[Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- this line is generated automatically for a new component
public class GlobalSoundSourcesController : Component
{

		private List<AmbientSource> ambientSounds = new List<AmbientSource>();

	private void Init()
	{
		AmbientSource ambient0 = new AmbientSource("sound0.mp3");
			ambient0.SourceMask = 1;
			ambient0.Loop = 1;
			ambient0.Play();
			ambientSounds.Add(ambient0);

			AmbientSource ambient1 = new AmbientSource("sound1.mp3");
			ambient1.SourceMask = 1;
			ambient1.Loop = 1;
			ambient1.Play();
			ambientSounds.Add(ambient1);

	}

	private void Update()
	{
		if (Input.IsKeyDown(Input.KEY.P))
			{
				GetAllSoundSources(out List<SoundSource> sources);
				PlaySourceChannel(0, sources, ambientSounds);
			}

			if (Input.IsKeyDown(Input.KEY.S))
			{
				GetAllSoundSources(out List<SoundSource> sources);
				StopSourceChannel(0, sources, ambientSounds);
			}
	}
		private void GetAllSoundSources(out List<SoundSource> sounds)
		{
			List<Node> nodes = new List<Node>();
			World.GetNodesByType((int)Node.TYPE.SOUND_SOURCE, nodes);

			sounds = new List<SoundSource>();
			foreach (var n in nodes)
				sounds.Add(n as SoundSource);
		}
		private void PlaySourceChannel(int number, in List<SoundSource> sounds)
		{
			foreach (var s in sounds)
			{
				if ((s.SourceMask & (1 << number)) != 0)
					s.Play();
			}
		}
		private void PlaySourceChannel(int number, in List<SoundSource> sources, in List<AmbientSource> ambients)
		{
			PlaySourceChannel(number, sources);

			foreach (var a in ambients)
			{
				if ((a.SourceMask & (1 << number)) != 0)
					a.Play();
			}
		}
		private void StopSourceChannel(int number, in List<SoundSource> sounds)
		{
			foreach (var s in sounds)
			{
				if ((s.SourceMask & (1 << number)) != 0)
					s.Stop();
			}
		}

		private void StopSourceChannel(int number, in List<SoundSource> sources, in List<AmbientSource> ambients)
		{
			StopSourceChannel(number, sources);

			foreach (var a in ambients)
			{
				if ((a.SourceMask & (1 << number)) != 0)
					a.Stop();
			}
		}
}
Last update: 13.12.2024
Build: ()