DevLog 20250611: Audio API Design for Divooka Glaze!

DevLog 20250611: Audio API Design for Divooka Glaze!

Glaze! is an interactive media framework in Divooka that encompasses a Processing-like interface.

Overview

Today, I’m laying the groundwork for audio APIs for our Glaze! framework.

Divooka Glaze! attracts inspiration from SFML and Processing, so we have to perceive how these two deal with audio first.

How SFML Handles It (SFML.Net)

To play audio in SFML.Net, we use the SFML.Audio module, which offers two major courses:

  1. Sound + SoundBuffer for brief, fully-loaded sounds (like sound results).
  2. Music for lengthy, streamed audio (like background music).

Playing Short Sounds

Short audio recordsdata (WAV, OGG, FLAC, and many others.) could be absolutely loaded into reminiscence:

// Load the complete file right into a buffer (solely do that as soon as per sound).
SoundBuffer buffer = new SoundBuffer("hit.wav");

// Create a Sound occasion and assign the buffer.
Sound hitSound = new Sound(buffer);

// Optional settings
hitSound.Volume = 75f;    // 0–100
hitSound.Pitch  = 1.2f;   // playback pace
hitSound.Loop   = false;  // play as soon as

// Play it
hitSound.Play();

// Make certain this system would not exit instantly,
// in any other case the sound shall be reduce off:
whereas (hitSound.Status == SoundStatus.Playing)
    System.Threading.Thread.Sleep(10);

Key factors:

  • Reuse the identical SoundBuffer if it is advisable play the identical sound a number of occasions.
  • Keep the Sound (and its SoundBuffer) in scope till playback finishes.

Streaming Music

For massive recordsdata (e.g., full-length tracks), use the Music class, which streams from disk:

  • It would not load the complete file into RAM.
  • Suitable for lengthy tracks, although with barely increased CPU utilization resulting from streaming.
// Create a Music occasion; it should stream the file on the fly.
Music backgroundMusic = new Music("background.ogg");

// Optional settings
backgroundMusic.Volume = 50f;
backgroundMusic.Loop   = true;

// Start playback
backgroundMusic.Play();

// In a sport loop we might usually:
// whereas (window.IsOpen()) { /* replace, draw, and many others. */ }

Common Pitfalls

  • Missing Native DLLs: If you get DllNotFoundException, guarantee all CSFML native libraries are current.
  • Scope & Lifetime: If Sound or Music goes out of scope (is rubbish collected), playback stops.
  • Program Exit: If the appliance ends earlier than the audio finishes, you will not hear the complete sound – preserve the primary thread working or combine playback into the render loop.

How Processing Handles It

Processing gives sound assist by means of the built-in Sound library and the legacy Minim library.

Below are the 2 most typical approaches.

The Built-in Sound Library

Installing/Importing

  1. In the Processing IDE, go to Sketch → Import Library… → Add Library…
  2. Search for “Sound”, then click on Install (if not already put in).

Placing Audio Files

  • Create a folder named knowledge within the sketch’s listing.
  • Copy audio recordsdata (e.g., music.mp3 or beat.wav) into that knowledge folder.

In the sketch, import and declare:

import processing.sound.*;
SoundFile tune;

void setup() {
  dimension(400, 200);
  // Load a file named "music.mp3" from /knowledge
  tune = new SoundFile(this, "music.mp3");
  tune.play();        // begin taking part in as soon as
}

void draw() {
  background(0);
  // (Optionally visualize or management playback right here)
}

Looping, Volume, Rate

void setup() {
  dimension(400, 200);
  tune = new SoundFile(this, "music.mp3");

  tune.loop();               // loop indefinitely
  tune.amp(0.5);             // set quantity (0.0–1.0)
  tune.price(1.2);            // change playback pace (1.0 = regular)
}

Minim

Minim handles issues equally, albeit by means of AudioPlayer:

import ddf.minim.*;
Minim minim;
AudioPlayer participant;

void setup() {
  dimension(400, 200);

  minim = new Minim(this);
  // loadFile(filename, bufferSize)
  participant = minim.loadFile("music.mp3", 2048); // Place MP3/WAV recordsdata contained in the sketch's `knowledge` folder.
  participant.play();

  // Looping & Controlling
  participant.loop();        // loop playback
  participant.setGain(-10);  // decrease quantity: acquire in dB
  participant.setTempo(1.5); // pace multiplier
}

void draw() {
  background(50);
  // ...
}
  • Where to Store Files: Always place audio recordsdata within the sketch’s knowledge/ folder so Processing can discover them.
  • File Formats:

    • Sound library: helps WAV, AIFF, MP3 (relying on platform).
    • Minim: helps MP3, OGG, WAV.
  • Latency / Real-Time: For low-latency playback or dwell audio enter/processing, Minim (or superior libraries like Beads or TarsosDSP) could also be preferable.
  • Visualizations: Both libraries assist real-time audio evaluation (waveforms, FFT), which is nice for interactive visuals.

Observations

Those two statements are essential:

// Load a soundfile from the /knowledge folder of the sketch and play it again
file = new SoundFile(this, "pattern.mp3");
file.play();

We can observe just a few issues concerning API design:

  1. It’s procedural and crucial – we create sources first, then set properties, then play/cease by way of the useful resource reference. Importantly, it is necessary to maintain a reference for later management.
  2. Resources may require specific (or scope-based) launch.

On the opposite hand, I’m extra concerned about a "useful" model API, like this:

Audio API Concept

The Approach

We might implicitly load and handle sources, releasing them on the finish of the appliance lifetime (on window shut), if no specific reference is required. However, distinguishing between SoundBuffer and Sound (each are IDisposable) could be tough when deciding which to persist. At the very least, that is what we must always expose by way of PlaySound() and PlayMusic().

Image description

non-public void LaunchResources()
{
    // Sounds
    foreach (Sound merchandise in _soundInstances)
        merchandise.Dispose();
    foreach ((string key, SoundBuffer merchandise) in _soundBuffers)
        merchandise.Dispose();
    foreach (Music merchandise in _music)
        merchandise.Dispose();
}

In truth within the present design we can’t share the underlying occasion – since Glaze! is implementation-agnostic – until we introduce strongly typed sorts for SoundBuffer, Sound, and Music, so all implementations can acknowledge them. Otherwise, we will not return any occasion objects.

// IInteractiveServiceProvider, which is unaware of SFML.Net's existence
#area Audio Engine
void PlaySound(string filePath);
void PlayMusic(string filePath, bool loop = true);
#endregion

A barely inelegant shortcut is to show them as untyped "object handles":

/// <abstract>
/// One-shot sound.
/// </abstract>
object PlaySound(string filePath);
/// <abstract>
/// Loopable BGM and many others.
/// </abstract>
object PlayMusic(string filePath, bool loop = true);
/// <param title="quantity">0–100f</param>
void SetVolume(object soundOrMusic, float quantity);
/// <param title="pitch">0–1f</param>
void SetPitch(object soundOrMusic, float pitch);
void SetLoop(object music, bool loop);

While it may appear "unsafe" on the paper, it really works properly in Divooka’s graphical interface:

Object Handle Looks Just Like Any Other Object on GUI - As If Strongly Typed

(This is partly because of Divooka’s assist for return worth naming by way of XML doc feedback, e.g., <returns title="Music">A music occasion.</returns> for PlayMusic().)

Conclusion

So far so good! There’s rather a lot we will improve within the audio engine – extra parameters, DSP assist, and many others. For instance, Processing has very neat features for low-pass/high-pass filters.

But for now, we will play sounds – and that is a strong begin!

References

HI-FI News

by way of DEV Community https://dev.to

June 11, 2025 at 06:17PM