This page has been translated automatically.
Видеоуроки
Интерфейс
Основы
Продвинутый уровень
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Профессиональный уровень (SIM)
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Физика
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Контроль версий
Настройки и предпочтения
Работа с проектами
Настройка параметров ноды
Setting Up Materials
Настройка свойств
Освещение
Sandworm
Использование инструментов редактора для конкретных задач
Расширение функционала редактора
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World-ноды
Звуковые объекты
Объекты поиска пути
Player-ноды
Программирование
Основы
Настройка среды разработки
C++
C#
UnigineScript
UUSL (Unified UNIGINE Shader Language)
Плагины
Форматы файлов
Материалы и шейдеры
Rebuilding the Engine Tools
Интерфейс пользователя (GUI)
Двойная точность координат
API
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
Работа с контентом
Оптимизация контента
Материалы
Визуальный редактор материалов
Сэмплы материалов
Material Nodes Library
Miscellaneous
Input
Math
Matrix
Textures
Art Samples
Учебные материалы
Внимание! Эта версия документация УСТАРЕЛА, поскольку относится к более ранней версии SDK! Пожалуйста, переключитесь на самую актуальную документацию для последней версии SDK.
Внимание! Эта версия документации описывает устаревшую версию SDK, которая больше не поддерживается! Пожалуйста, обновитесь до последней версии SDK.

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++)
int AppWorldLogic::init()
{
	AmbientSourcePtr ambient_0 = AmbientSource::create("sound0.mp3");
	ambient_0->setSourceMask(1);
	ambient_0->setLoop(1);
	ambient_0->play();

	return 1;
}

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++)
void getAllSoundSources(Vector<SoundSourcePtr> &out_sounds)
{
	Vector<NodePtr> nodes;
	World::getNodesByType(Node::SOUND_SOURCE, nodes);

	out_sounds.clear();
	for (auto &n : nodes)
		out_sounds.append(checked_ptr_cast<SoundSource>(n));
}

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

Source code (C++)
private:
	Unigine::Vector<Unigine::AmbientSourcePtr> ambient_sounds;

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

Source code (C++)
ambient_sounds.append(ambient_0);

Controlling the Playback#

We can control the playback via the SoundSource and the AmbientSource class methods play(), stop(), and setTime(). 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++)
void playSourceChannel(int number, const Vector<SoundSourcePtr> &sounds)
{
	for (auto &s : sounds)
	{
		if (s->getSourceMask() & (1 << number))
			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++)
void playSourceChannel(int number, const Vector<SoundSourcePtr> &sources, const Vector<AmbientSourcePtr> &ambients)
{
	playSourceChannel(number, sources);

	for (auto &a : ambients)
	{
		if (a->getSourceMask() & (1 << number))
			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++)
void stopSourceChannel(int number, const Vector<SoundSourcePtr> &sounds)
{
	for (auto &s : sounds)
	{
		if (s->getSourceMask() & (1 << number))
			s->stop();
	}
}

void stopSourceChannel(int number, const Vector<SoundSourcePtr> &sources, const Vector<AmbientSourcePtr> &ambients)
{
	stopSourceChannel(number, sources);

	for (auto &a : ambients)
	{
		if (a->getSourceMask() & (1 << number))
			a->stop();
	}
}

The only thing left is to bind methods and buttons:

Source code (C++)
int AppWorldLogic::update()
{
	if (Input::isKeyDown(Input::KEY_P))
	{
		Vector<SoundSourcePtr> sources;
		getAllSoundSources(sources);
		playSourceChannel(0, sources, ambient_sounds);
	}

	if (Input::isKeyDown(Input::KEY_S))
	{
		Vector<SoundSourcePtr> sources;
		getAllSoundSources(sources);
		stopSourceChannel(0, sources, ambient_sounds);
	}

	return 1;
}

Code Sample#

Here's a complete code:

Source code (C++)
#include <UnigineLogic.h>
#include <UnigineVector.h>
#include <UnigineSounds.h>

class AppWorldLogic : public Unigine::WorldLogic
{

public:
	AppWorldLogic() {}
	virtual ~AppWorldLogic() {}

	int init() override;
	int update() override;

private:
	Unigine::Vector<Unigine::AmbientSourcePtr> ambient_sounds;
};
Source code (C++)
#include "AppWorldLogic.h"
#include <UnigineWorld.h>
#include <UnigineInput.h>

using namespace Unigine;

void getAllSoundSources(Vector<SoundSourcePtr> &out_sounds)
{
	Vector<NodePtr> nodes;
	World::getNodesByType(Node::SOUND_SOURCE, nodes);

	out_sounds.clear();
	for (auto &n : nodes)
		out_sounds.append(checked_ptr_cast<SoundSource>(n));
}

void playSourceChannel(int number, const Vector<SoundSourcePtr> &sounds)
{
	for (auto &s : sounds)
	{
		if (s->getSourceMask() & (1 << number))
			s->play();
	}
}

void playSourceChannel(int number, const Vector<SoundSourcePtr> &sources, const Vector<AmbientSourcePtr> &ambients)
{
	playSourceChannel(number, sources);

	for (auto &a : ambients)
	{
		if (a->getSourceMask() & (1 << number))
			a->play();
	}
}

void stopSourceChannel(int number, const Vector<SoundSourcePtr> &sounds)
{
	for (auto &s : sounds)
	{
		if (s->getSourceMask() & (1 << number))
			s->stop();
	}
}

void stopSourceChannel(int number, const Vector<SoundSourcePtr> &sources, const Vector<AmbientSourcePtr> &ambients)
{
	stopSourceChannel(number, sources);

	for (auto &a : ambients)
	{
		if (a->getSourceMask() & (1 << number))
			a->stop();
	}
}

int AppWorldLogic::init()
{
	AmbientSourcePtr ambient_0 = AmbientSource::create("sound0.mp3");
	ambient_0->setSourceMask(1);
	ambient_0->setLoop(1);
	ambient_0->play();
	ambient_sounds.append(ambient_0);

	AmbientSourcePtr ambient_1 = AmbientSource::create("sound1.mp3");
	ambient_1->setSourceMask(1);
	ambient_1->setLoop(1);
	ambient_1->play();
	ambient_sounds.append(ambient_1);

	return 1;
}

int AppWorldLogic::update()
{
	if (Input::isKeyDown(Input::KEY_P))
	{
		Vector<SoundSourcePtr> sources;
		getAllSoundSources(sources);
		playSourceChannel(0, sources, ambient_sounds);
	}

	if (Input::isKeyDown(Input::KEY_S))
	{
		Vector<SoundSourcePtr> sources;
		getAllSoundSources(sources);
		stopSourceChannel(0, sources, ambient_sounds);
	}

	return 1;
}
Last update: 23.06.2023
Build: ()