Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing simple sounds in a Windows Store (Metro) application

I am building a Windows Store (Metro) application using XAML and C#. I would like to play a simple tone and be able to control the duration and pitch; the kind of thing we used to do with Console.Beep.

I found Play dynamically-created simple sounds in C# without external libraries but it references SoundPlayer (System.Media namespace) which doesn't appear to be supported for this type of application (unless of course I am missing something).

Does anyone have an example of generating a sound (not playing a wav file) in a metro app?

like image 832
JonnyBoats Avatar asked Jun 17 '13 01:06

JonnyBoats


1 Answers

Based on this article, below works OK for me:

public async Task<IRandomAccessStream> BeepBeep(int Amplitude, int Frequency, int Duration)
{
    double A = ((Amplitude * (System.Math.Pow(2, 15))) / 1000) - 1;
    double DeltaFT = 2 * Math.PI * Frequency / 44100.0;

    int Samples = 441 * Duration / 10;
    int Bytes = Samples * 4;
    int[] Hdr = { 0X46464952, 36 + Bytes, 0X45564157, 0X20746D66, 16, 0X20001, 44100, 176400, 0X100004, 0X61746164, Bytes };

    InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
    IOutputStream outStream = ims.GetOutputStreamAt(0);
    DataWriter dw = new DataWriter(outStream);
    dw.ByteOrder = ByteOrder.LittleEndian;

    for (int I = 0; I < Hdr.Length; I++)
    {
        dw.WriteInt32(Hdr[I]);
    }
    for (int T = 0; T < Samples; T++)
    {
        short Sample = System.Convert.ToInt16(A * Math.Sin(DeltaFT * T));
        dw.WriteInt16(Sample);
        dw.WriteInt16(Sample);
    }
    await dw.StoreAsync();
    await outStream.FlushAsync();
    return ims;
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var beepStream = await BeepBeep(200, 3000, 250);
    mediaElement1.SetSource(beepStream, string.Empty);
    mediaElement1.Play();
}

It uses MediaElement for playback but, since the source is an auto generated IRandomAccessStream, it's flexible.

like image 95
StaWho Avatar answered Nov 16 '22 03:11

StaWho