Using the new Audiograph API to play WAV, WMA and MP3 files in a Windows 10 Universal App

Windows 10 introduces a native way to play audio files with C#. This will save you a lot of time as you dont need to dive into DirectX or SharpDX anymore!

Do you remember the XNA SoundEffect? It provided a super easy way to play short audio clips in Silverlight apps. Unfortunately when WinRT came out, you basically had to fall back on using Native DirectX of third party libraries like SharpDX.

The new AudioGraph in Windows 10 introduces a native way to use Audio in your Universal Apps using C#. The following demo project creates an AudioGraph and adds multiple audio files to it which can be played in a fire-and-forget way.

win10 audio

Wav, WMA, MP3

The demo project plays Wave, WMA and MP3 files. Download it on Github or just add the following class to your project:

public class AudioPlayer {
    private AudioGraph _graph;
    private Dictionary<string, AudioFileInputNode> _fileInputs = new Dictionary<string, AudioFileInputNode>();
    private AudioDeviceOutputNode _deviceOutput;

    public async Task LoadFileAsync(IStorageFile file) {
        if (_deviceOutput == null) {
            await CreateAudioGraph();
        }

        var fileInputResult = await _graph.CreateFileInputNodeAsync(file);

        _fileInputs.Add(file.Name, fileInputResult.FileInputNode);
        fileInputResult.FileInputNode.Stop();
        fileInputResult.FileInputNode.AddOutgoingConnection(_deviceOutput);
    }

    public void Play(string key, double gain) {
        var sound = _fileInputs[key];
        sound.OutgoingGain = gain;
        sound.Seek(TimeSpan.Zero);
        sound.Start();
    }

    private async Task CreateAudioGraph() {
        var settings = new AudioGraphSettings(AudioRenderCategory.Media);
        var result = await AudioGraph.CreateAsync(settings);
        _graph = result.Graph;
        var deviceOutputNodeResult = await _graph.CreateDeviceOutputNodeAsync();
        _deviceOutput = deviceOutputNodeResult.DeviceOutputNode;
        _graph.ResetAllNodes();
        _graph.Start();
    }
}

And use it like this:

var wav = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Audio/washburn.wav"));
var player = new AudioPlayer();
await player.LoadFileAsync(wav);
player.Play("washburn.wav", 0.5);

I tested the code in my Mahjong game and so far it performs really well. If you have any comments or questions, please send me an email. Happy wave-making!