I’ve been working on Silverlight for a couple of years now, and finally decided to start talking about it in my blog. With the recent beta, we’ve added raw A/V support to Silverlight 3, and that means not only that people will be able to write their own decoders for Silverlight, but also that they can now play back PCM audio through managed code. The easiest way to get PCM data is simply to use a Wave file. Wave files are a container format for multiple audio encodings, so not all files will play back in Silverlight, but the PCM encoded ones will. To help out, I’ve published a sample MediaStreamSource implementation on Code Gallery (http://code.msdn.microsoft.com/wavmss).

The easiest way to try out the code is to open a local wave file from your drive using the OpenFileDialog (C:\Windows\Media has a bunch of little sound bites).

private void Button_Click(object sender, RoutedEventArgs e) 
{
    OpenFileDialog ofd = new OpenFileDialog(); 

    if (ofd.ShowDialog().Value)
    {
        Stream s = ofd.File.OpenRead();
        WaveMediaStreamSource wavMss = new WaveMediaStreamSource(s);
        try
        {
            me.SetSource(wavMss);
        }
        catch (InvalidOperationException)
        {
            // This file is not valid
        }
    }
} 

This snippet will play the wave file right away. Remember that to get the FileOpenDialog, you need to hook the handler to a user initiated action. An easy way for this, is to put a MediaElement and a button on a page.

<UserControl x:Class="SampleWave.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <MediaElement Name="me"/>
        <Button Name="b" Width="200" Height="20" Content="Open" Click="Button_Click"/>
    </Grid>
</UserControl>

That’s it, you can now play wave files.