← Tutorials

Sound and music

This tutorial takes about twenty minutes. You need Turian installed and the first tutorial done. You also need two short WAV files: copy Click.wav and Ambient.wav from example-15-audio/Assets, or use your own.

Audio is split into two bricks. org.mass4.turian.audio routes sound events and voices, and org.mass4.turian.audio.miniaudio opens the output device and decodes WAV files. The audio brick's own documentation says a backend is needed for audible output, so install both.

1. Create a project

turian-cli new SoundPlayground
turian-studio --project SoundPlayground

Open Assets/scene-01.prefab by double-clicking it in the Assets panel.

2. Install the audio bricks

In Studio, open Project → Bricks… and add org.mass4.turian.audio and org.mass4.turian.audio.miniaudio.

From a terminal, run:

turian-cli brick add org.mass4.turian.audio --project SoundPlayground
turian-cli brick add org.mass4.turian.audio.miniaudio --project SoundPlayground
turian-cli brick list --project SoundPlayground

The list shows both bricks. If brick add cannot find them in the registry, add them from local checkouts with file:/path/to/<brick> after the id, as shown in Bricks.

3. Import the clips

Copy Click.wav and Ambient.wav into the project's Assets folder. Turian imports files as they change, and each clip gets a .meta file beside it that holds its id. Both clips appear in the Assets panel.

Keep the .meta files under version control; the events in the next step refer to clips by those ids.

4. Create two audio events

An audio event is a named sound with its settings: which clips it plays, its volume, whether it loops and whether it streams from disk. Create one from the Assets panel: right-click, then New → Audio → Audio Event.

Name the first asset Click. In the Inspector, set EventName to tutorial.click, drag Click.wav into Clips and set Volume to 0.5.

Create a second event and name it Music. Set EventName to tutorial.music, add Ambient.wav to Clips, and turn on Loop and Stream. Streaming decodes the file as it plays rather than all at once, which suits long tracks. Set Volume to 0.3.

The event's Bus defaults to SFX. You do not need to change it yet; see step 7.

The Assets panel listing the Click and Music audio events beside the Click and Ambient clips.

5. Play a sound from a script

Create Assets/SoundPlayer.cs. The audio types come from the Turian.Audio namespace and the service lookup from Microsoft.Extensions.DependencyInjection, so both need a using:

using System.Text.Json.Serialization;
using Microsoft.Extensions.DependencyInjection;
using Turian.Audio;

namespace Usercode;

/// <summary>Plays a click on Space, loops background music and lets Up and Down change the music's volume.</summary>
public sealed class SoundPlayer : Component
{
    IAudioService? audio;
    string click = string.Empty;
    string music = string.Empty;
    VoiceHandle musicVoice;
    float musicVolume = 0.3f;

    /// <summary>The short sound played on Space.</summary>
    public DataAssetReference<AudioEvent>? ClickEvent { get; set; }

    /// <summary>The looping background track.</summary>
    public DataAssetReference<AudioEvent>? MusicEvent { get; set; }

    /// <summary>The optional player input.</summary>
    [InjectService(Optional = true), JsonIgnore]
    public IInputSource? Input { get; private set; }

    public override void OnStart()
    {
        audio = Services?.GetService<IAudioService>();
        if (audio is null)
        {
            return;
        }

        click = audio.Prepare(ClickEvent ?? throw new InvalidOperationException("Assign ClickEvent."));
        music = audio.Prepare(MusicEvent ?? throw new InvalidOperationException("Assign MusicEvent."));
        musicVoice = audio.Post(music, Id, new AudioParameterSet { Volume = musicVolume });
    }

    public override void OnUpdate(float deltaTime)
    {
        if (audio is null || Input is null)
        {
            return;
        }

        if (Input.WasKeyPressed(Key.Space))
        {
            audio.Post(click, Id, new AudioParameterSet());
        }

        var direction = (Input.IsKeyDown(Key.Up) ? 1f : 0f) - (Input.IsKeyDown(Key.Down) ? 1f : 0f);
        if (direction != 0 && musicVoice.Value != 0)
        {
            musicVolume = Math.Clamp(musicVolume + direction * 0.5f * deltaTime, 0f, 1f);
            audio.SetParameters(musicVoice, new AudioParameterSet { Volume = musicVolume });
        }
    }

    public override void OnDisable() => audio?.StopAll(Id);
}

Prepare loads an event and its clips outside the audio callback, so the sound is ready when you post it. Post starts a voice and returns a VoiceHandle that you can use to change it later. Post also returns an invalid handle, whose Value is 0, when the command queue is full, which is why the script checks the handle before using it.

Save the file, then add it to a node. Create an empty node named Sound with New Node, drag SoundPlayer.cs onto it, and drag Click onto the Click Event slot and Music onto the Music Event slot in the Inspector. The slots are named after the properties in the script.

6. Play it

Press F5. The music starts as the scene starts, and it loops until you stop Play.

Click inside the Game view so it receives the keyboard. Press Space to play the click. Hold Up or Down to change the music's volume; it moves between 0 and 1 at half a unit per second. Escape hands the keyboard back to Studio.

Press F5 again to stop. OnDisable stops every voice the component started, so nothing keeps playing after Play ends.

7. Route music to its own bus (optional)

Events are sent to a mixer bus. Buses let you set the volume of a whole group, such as all music, in one place. Buses are defined by an Audio Mixer asset. A new one starts with the buses Master, Music, SFX, Voice and UI, the same five that Turian uses when no mixer is set.

Create an Audio → Audio Mixer asset from the Assets panel. Then create Settings → Audio Settings (example-15-audio has one) and set its Mixer to the mixer asset. Set the Music event's Bus to Music.

To change the bus from script, get the mixer service and call SetBusVolume with the bus name. The bus name is case-sensitive:

var mixer = Services!.GetRequiredService<IAudioMixerService>();
mixer.SetBusVolume("Music", 0.5f);

The audio brick's own documentation covers the rest of the mixer: effects, snapshots and meters.

Next steps

  • Physics playground — rigidbodies, colliders and a ragdoll.
  • Components — the component model behind these scripts.
  • Assets — imports, .meta files and data assets.
  • Input — rebindable controls and gamepads instead of fixed keys.
  • Bricks — installing, forking and publishing bricks.

The examples go further: example-16-audio-showcase streams MP3 and FLAC music, with snapshots and a settings screen bound to the mixer.

Edit this page