Universal Windows Platform – Sound Game

Sound Game demonstrates how to create a simple game to play sounds using a MediaElement with a provided frequency as an audio stream.

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class Library
{
    private readonly Dictionary<string, double> _notes = new Dictionary<string, double>()
    {
        { "C", 261.6 }, { "C#", 277.2 }, { "D", 293.7 },
        { "D#", 311.1 } , { "E", 329.6 }, { "F", 349.2 },
        { "F#", 370.0 }, { "G", 392.0 }, { "G#", 415.3 },
        { "A", 440.0 }, { "A#", 466.2 }, { "B", 493.9 }
    };

    private void Play(double note)
    {
        MediaElement playback = new MediaElement();
        IRandomAccessStream stream = new InMemoryRandomAccessStream();
        BinaryWriter writer = new BinaryWriter(stream.AsStream());
        int formatChunkSize = 16;
        int headerSize = 8;
        short formatType = 1;
        short tracks = 1;
        int samplesPerSecond = 44100;
        short bitsPerSample = 16;
        short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));
        int bytesPerSecond = samplesPerSecond * frameSize;
        int waveSize = 4;
        int data = 0x61746164;
        int samples = 88200 * 4;
        int dataChunkSize = samples * frameSize;
        int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;
        double frequency = note * 1.5;
        writer.Write(0x46464952); // RIFF
        writer.Write(fileSize);
        writer.Write(0x45564157); // WAVE
        writer.Write(0x20746D66); // Format
        writer.Write(formatChunkSize);
        writer.Write(formatType);
        writer.Write(tracks);
        writer.Write(samplesPerSecond);
        writer.Write(bytesPerSecond);
        writer.Write(frameSize);
        writer.Write(bitsPerSample);
        writer.Write(data);
        writer.Write(dataChunkSize);
        for (int i = 0; i < samples / 4; i++)
        {
            double t = (double)i / (double)samplesPerSecond;
            short s = (short)(10000 * (Math.Sin(t * frequency * 2.0 * Math.PI)));
            writer.Write(s);
        }
        stream.Seek(0);
        playback.SetSource(stream, "audio/wav");
        playback.Play();
    }

    private void Add(Grid grid, int column)
    {
        Button button = new Button()
        {
            Height = 80,
            Width = 20,
            FontSize = 10,
            Padding = new Thickness(0),
            Content = _notes.Keys.ElementAt(column),
            Margin = new Thickness(5)
        };
        button.Click += (object sender, RoutedEventArgs e) =>
        {
            button = (Button)sender;
            int note = Grid.GetColumn(button);
            Play(_notes[_notes.Keys.ElementAt(note)]);
        };
        button.SetValue(Grid.ColumnProperty, column);
        grid.Children.Add(button);
    }

    private void Layout(ref Grid Grid)
    {
        Grid.Children.Clear();
        Grid.ColumnDefinitions.Clear();
        Grid.RowDefinitions.Clear();
        // Setup Grid
        for (int Column = 0; (Column < _notes.Count); Column++)
        {
            Grid.ColumnDefinitions.Add(new ColumnDefinition());
            Add(Grid, Column);
        }
    }

    public void New(ref Grid grid)
    {
        Layout(ref grid);
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is a Dictionary of string and double to store the musical notes that will be played and their approximate audio frequency. The Play Method is used to play a musical note with a MediaElement and a InMemoryRandomAccessStream which will be used to help create the audio with a BinaryWriter to create a WAVE audio stream that will be written to with the given frequency to produce the Samples that will create the required musical note.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<Viewbox>
	<Grid Margin="50" Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Viewbox>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="New" Icon="Page2" Label="New" Click="New_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a ViewBox containing a Grid Control that will be the look-and-feel of the game. The second block of XAML is is the CommandBar which contains New – to start the game.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

private void New_Click(object sender, RoutedEventArgs e)
{
	library.New(ref Display);
}

Below the MainPage() Method an instance of the Library Class is created, then New_Click is used to call the New method to setup the game in the Library Class

Step 13

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 14

After the Application has started running use New to start then can Play sounds by tapping the buttons in the Application.

ran-sound-game

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s