How to make a Windows Store game with C# and XAML, part 5

In this mini post we’ll be finally adding some sounds to our game. You will need to have some sound effects added to your Assets -folder. You need one for laser shooting and one for enemy hit sound. One place you could download some of these for free is Free game content resources. Add one with the name pew.mp3 under Assets (right click, add existing..) and one with the name pow.mp3

Windows 10 finally brings an easy way to add low latency sound to your universal app with managed classes, without need to do interop with DirectX. The main class is AudioGraph and it is good replacement for XAudio2.

We nee to edit GamePage.xaml.cs and add first three using statements, first of them is not needed for the sound but just to get some debug output in case something goes wrong with the initialization of the audio.

using Windows.Media.Audio;
using System.Diagnostics;
using Windows.Storage;
using Windows.Media.Render;

Now we need to add the member variables which will be used to play the audio, and store the audio files in the memory. AudioGraph class is for the audio playing, AudioDeviceOutputNode is the output device where the sound is played and the AudioFileInputNode has the sound file. These go as member variables to GamePage class, add them under the bool fireSuppressor:

private AudioGraph graph;
private AudioDeviceOutputNode deviceOutput;
private Dictionary<string, AudioFileInputNode> fileInputs = new Dictionary<string, AudioFileInputNode>();

In the Loaded we need to add the the following:

InitSound();

Next we need to add the method itself, which will create the audio pipeline, load the sounds and enable us to play them later on:

private async System.Threading.Tasks.Task InitSound()
{
    AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media);
    CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings);

    if (result.Status == AudioGraphCreationStatus.Success)
    {
        graph = result.Graph;

        // Create the output device for audio playing
        CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await graph.CreateDeviceOutputNodeAsync();

        // Ensure there's audio output ready and available
        if (deviceOutputNodeResult.Status == AudioDeviceNodeCreationStatus.Success)
        {
            deviceOutput = deviceOutputNodeResult.DeviceOutputNode;
            graph.ResetAllNodes();

            await AddFileToSounds("ms-appx:///Assets/pew.mp3");
            await AddFileToSounds("ms-appx:///Assets/Pop.mp3");
            // here you could list all your sounds like row above

            graph.Start();
        }
    }
}

Add this method, which adds a given sample to memory for playing later on:

/// <summary>
/// Load and add resource sound file to memory dictionary for playing
/// </summary>
/// <returns></return>
private async System.Threading.Tasks.Task AddFileToSounds(string uri)
{
    var soundFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(uri));
    CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(soundFile);

    if (AudioFileNodeCreationStatus.Success == fileInputResult.Status)
    {
        fileInputs.Add(soundFile.Name, fileInputResult.FileInputNode);
        fileInputResult.FileInputNode.Stop();
        fileInputResult.FileInputNode.AddOutgoingConnection(deviceOutput);
    }
}

That is all what is needed for setting up playing sounds. Next job for us is to hook the sound playing in the correct places in the code and play the actual sounds. Go to OnFire methos and add the following under bullets.Add(bullet); :

// Play the sound
var pew = fileInputs["pew.mp3"];
pew.Reset();
pew.Start();

The previous code is code to play the shooting sound, now we add the explosion sound for hitting enemy. Go to the HitTest and add under the enemies[i].Dead = true; the following code:

// Play the sound
var pop = fileInputs["Pop.mp3"];
pop.Reset();
pop.Start();

That’s all, now just compile and run the game, and enjoy your sound effects on the game! On the next blog post we’ll be talking about scaling the app on different screens properly, doing the Windows 10 adaptive screen magic.

About Jani Nevalainen

Windows developer who's been working on Microsoft Platforms since 1996. Windows Phone dev MVP 2013, Windows Development Platform MVP 2014. Currently working as Technical Evangelist for Microsoft Finland Developer Experience team.
This entry was posted in AudioGraph, Sound, Universal Apps, UWP, Windows 10, Windows Phone. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *