Search code examples
silverlightaudiomp3

How can a silverlight app download and play an mp3 file from a URL?


I have a small Silverlight app which downloads all of the images and text it needs from a URL, like this:

if (dataItem.Kind == DataItemKind.BitmapImage)
{
    WebClient webClientBitmapImageLoader = new WebClient();
    webClientBitmapImageLoader.OpenReadCompleted += new OpenReadCompletedEventHandler(webClientBitmapImageLoader_OpenReadCompleted);
    webClientBitmapImageLoader.OpenReadAsync(new Uri(dataItem.SourceUri, UriKind.Absolute), dataItem);
}
else if (dataItem.Kind == DataItemKind.TextFile)
{
    WebClient webClientTextFileLoader = new WebClient();
    webClientTextFileLoader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientTextFileLoader_DownloadStringCompleted);
    webClientTextFileLoader.DownloadStringAsync(new Uri(dataItem.SourceUri, UriKind.Absolute), dataItem);
}

and:

void webClientBitmapImageLoader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.SetSource(e.Result);
    DataItem dataItem = e.UserState as DataItem;

    CompleteItemLoadedProcess(dataItem, bitmapImage);
}

void webClientTextFileLoader_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    DataItem dataItem = e.UserState as DataItem;
    string textFileContent = e.Result.ForceWindowLineBreaks();
    CompleteItemLoadedProcess(dataItem, textFileContent);
}

Each of the images and text files are then put in a dictionary so that the application has access to them at any time. This works well.

Now I want to do the same with mp3 files, but all information I find on the web about playing mp3 files in Silverlight shows how to embed them in the .xap file, which I don't want to do since I wouldn't be able to download them dynamically as I do above.

How can I download and play mp3 files in Silverlight like I download and show images and text?


Solution

  • You would download the MP3 as binary stream and store the result in a byte array. Its this byte array you would store in your dictionary.

    At the point that you want to assign the byte array to a MediaElement you would use code like this:-

    void SetMediaElementSource(MediaElement me, byte[] mp3)
    {
      me.SetSource(new MemoryStream(mp3));
    }