Skip to content

File Reading

Axwabo edited this page Aug 20, 2025 · 1 revision

File Reading

Important

Do not keep long audio files in memory. Stream them from the disk instead.

SecretLabNAudio.Core supports wav and aiff file reading by default. Install the full plugin, or the NLayer (mp3) and/or NVorbis (ogg) modules separately for more formats. Instructions are in the README

A WaveStream is a (usually) repositionable class that provides PCM data from files (or other sources).

(Try)CreateAudioReader

These two classes allow you to easily create a WaveStream (and an ISampleProvider).

Caution

Before using these classes, make sure the file exists by calling File.Exists

Important

Make sure to dispose of audio resources when you're done using them. You can invoke the dispose method manually, or use the DisposeOnDestroy extension method to automatically dispose of the WaveStream when the audio player is destroyed.

The CreateAudioReader class throws if no factory is found or if the factory doesn't return requested resources. Consider calling methods from TryCreateAudioReader with if statements. The latter methods return a bool indicating success and the requested resources as nullable out parameters.

List of methods:

  • WaveStream Stream(path) - automatic file type detection
  • WaveStream Stream(source, fileType, closeOnDispose) - creates a WaveStream from a user-handled Stream
  • ISampleProvider Provider(stream, fileType, closeOnDispose, convertStream) - stream must be handled by the user
  • (WaveStream, ISampleProvider) StreamAndProvider(path) - stream and a corresponding sample provider
  • (WaveStream, ISampleProvider) StreamAndProvider(source, fileType, closeOnDispose) - stream must be handled by the user

Example:

using SecretLabNAudio.Core.Extensions;
using SecretLabNAudio.Core.FileReading;

// consider using the ShortClipCache for storing small clips

using var stream = CreateAudioReader.Stream("path/to/file.wav");
RawSourceSampleProvider rawOriginal = stream.ReadSamples();
RawSourceSampleProvider rawCompatible = stream.ReadPlayerCompatibleSamples();
// stream is automatically disposed at the end of the code block, samples are in memory

The closeOnDispose parameter sets whether to close the original stream when the WaveStream is disposed. SecretLabNAudio internally wraps some built-in streams to support this parameter.

ShortClipCache

Important

Do not keep long audio files in memory. Stream them from the disk instead.

This is a centralized cache for storing short audio clips in the form of RawSourceSampleProvider objects. It skips nonexistent files without throwing an exception.

Keys are case-insensitive (ignore case). File audio is automatically converted to be compatible with players.

You can keep the extension in the key by setting the trimExtension parameter to false

The TryGet method returns a copy of the original, which references the same buffer. This allows for repositioning of each individual copy obtained from the cache.

Example:

using System.IO;
using SecretLabNAudio.Core;
using SecretLabNAudio.Core.Extensions;
using SecretLabNAudio.Core.FileReading;
using SecretLabNAudio.Core.Providers;

public static void CacheSoundEffects(string directory)
{
    ShortClipCache.AddFromFile(Path.Combine(directory, "pickup.wav"));
    ShortClipCache.AddFromFile(Path.Combine(directory, "drop.mp3"));
    ShortClipCache.AddFromFile(Path.Combine(directory, "use.ogg"));
    // or
    ShortClipCache.AddAllFromFiles(
        directory,
        true,
        "pickup.wav",
        "drop.mp3",
        "use.ogg"
    );
}

public static void PlayPickup(AudioPlayer player)
{
    player.AddMixerShortClip("pickUp"); // case does not matter
    // or
    if (ShortClipCache.TryGet("pickup", out RawSourceSampleProvider? provider))
        player.AddMixerInput(provider);
}

Audio Reader Factories

The IAudioReaderFactory defines methods to create WaveStreams and/or ISampleProviders, given a path or a Stream

Both methods return an AudioReaderFactoryResult which has an implicit conversion from a WaveStream that sets the provider using ToSampleProvider

public AudioReaderFactoryResult FromPath(string path) => new WaveFileReader(path);
// is the same as
public AudioReaderFactoryResult FromPath(string path) 
{
    var reader =  new WaveFileReader(path);
    return new AudioReaderFactoryResult(reader, reader.ToSampleProvider());
}

SecretLabNAudio.Core includes a factory for wav and aiff files. To register mp3 and ogg factories, install the full plugin or the required modules:

  • SecretLabNAudio.NLayer for mp3 support
  • SecretLabNAudio.NVorbis for ogg support

Custom Factories

Implement the IAudioReaderFactory interface and pass an instance to AudioReaderFactoryManager.RegisterFactory with the flie type.

Clone this wiki locally