Random geekery since 2005.

Husband, father, programmer, speaker, writer, blogger, podcaster, collector, traveler, golfer.

31 Days of Mango | Day #28: Media Library

Written in



This article is Day #28 in a series called 31 Days of Mango, and was written by guest author Jeff Fansler. Jeff can be reached on Twitter at @fanzoo.

Today we are going to take a look at the MediaLibrary class that is part of the Microsoft.Xna.Framework.Media namespace. As the name suggests, this class gives us access into the users Media Library. A Media Library on Windows Phone stores pictures and music. By using the Media Library you can integrate this content into your own applications. There are several reasons a developer may want to do this. Here are a few ideas:

  • To show the user a list of songs and let them select the background music while using your app.
  • To allow the user to download their images from a service (i.e. Flickr) and add them to the Media Library.
  • To use music artist or genre data from the Media Library to make suggestions on other similar content the user may be interested in.

In order to show how to use the Media Library I’ve created a sample application. This app will list all the songs that are in the user’s Media Library, play a song when the user selects a song, and allow the user to select an image from the Media Library to use as the background. The app uses the Media Library to get a list of songs and it also saves an image to the Media Library for the user.


Saving an Image to the Media Library

In the sample app I have added image1.jpg as a resource. It’s an awesome image and I’m sure all of the users are going to want it so we are going to save this image to the Media Library. The sample app saves this image in the Application_Launching method in the App.xaml.cs. Here is the code that does this work:

var library = new MediaLibrary();
var image = library.Pictures.Where(p => p.Name == imageName).SingleOrDefault();

if (image == null)
    var resource =
        .GetResourceStream(new Uri(string.Format("/31DaysMediaLibrary;component/Images/{0}",
    var bitmap = new BitmapImage();

    // Save the image to the camera roll or saved pictures album.
    library.SavePicture(imageName, bitmap.ToStream());

Most of this code is simply working with loading the image. There are a few important lines here that are using the Media Library. Let’s take a closer look at a few of these lines.

var library = new MediaLibrary();

This line creates a new MediaLibrary class. This is what will give you access to the Media Library properties and methods.

var image = library.Pictures.Where(p => p.Name == imageName).SingleOrDefault();

This line searches the library for any pictures that are saved with the imageName. If that image exists already, the code does not save it again.

library.SavePicture(imageName, bitmap.ToStream());

This line saves the BitmapImage to the library. You may notice that a BitmapImage doesn’t normally have a ToStream method. I think it should so I’ve used an extension method to add it. The extension class doesn’t have anything to do with the Media Library but here it is so you know how it works:

public static class BitmapExtensions
    public static Stream ToStream(this BitmapImage bitmap)
        var writeableBitmap = new WriteableBitmap(bitmap);
        var stream = new MemoryStream();
        writeableBitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
        stream.Position = 0;
        return stream;

After that code is executed, the image will be accessible in the Media Library. To show this in our sample app you can click the gear icon in the app tray and the new image will be available to be selected using a PhotoChooserTask.


Getting a List of Songs

In the sample app the screen shows a list of the songs that are in the user’s Media Library. The list is a ListBox. A DataTemplate is defined that binds the Text property of two TextBlock’s. One displays the song title and the other displays the artist. Here is what the XAML looks like for the ListBox:

                    Text="{Binding Name}"
                    Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                    Text="{Binding Artist.Name}"
                    Style="{StaticResource PhoneTextSubtleStyle}"/>

Setting the ItemsSource to the list of songs is quite simple:

var library = new MediaLibrary();
lstSongs.ItemsSource = library.Songs;

What Else Is There?

There are a few other properties off of the MediaLibrary class to take a look at:

Albums – This is similar to the Songs collection but lists albums instead.

Artists – Just like the Albums collection, this collection lists the artists of the songs.

Genres – This collection lists the genres of the songs.

Playlists – This collection lists the playlists that the user has added to their library.


As you can see, using the Media Library is quite easy. Most of the code in the sample app is written to use the content, not to access it from the library. I talked about how to access the Songs collection and how to save an image to the library. I discussed a few ways to use the library in your own apps. I’m sure there are many other ways to use this content. Have fun and I can’t wait to see your apps.

To download a full Windows Phone project that includes all of the code and concepts from this article, click the Download Code button below.


Tomorrow, we will cover globalization/localization in the article, and show you how easy it is to include this in your Windows Phone project.  See you then!



4 responses to “31 Days of Mango | Day #28: Media Library”

  1. […] Der Originalartikel befindet sich hier: Day #28: Media Library. […]

  2. […] /* 0) { ratingctl00_cphMiddle_cphContent_tr3w45fwwvre_itemRating = result['Rating']; SetCurrentRating('ctl00_cphMiddle_cphContent_tr3w45fwwvre_itemRating_pnlHolder', result['Rating'], "disabled fullStar", "disabled emptyStar", true); if(votesCountctl00_cphMiddle_cphContent_tr3w45fwwvre_itemRating!=null) { votesCountctl00_cphMiddle_cphContent_tr3w45fwwvre_itemRating ++; SetVotesCount('ctl00_cphMiddle_cphContent_tr3w45fwwvre_itemRating_lblUsersRated', '(' + votesCountctl00_cphMiddle_cphContent_tr3w45fwwvre_itemRating + ' votes)'); } SetRatingCookie('r', 'i28240', '1'); } else if (result['Status'] == 1) { alert('The session has expired. Please refresh the page to be able to vote!'); } } /* ]]> */ (0 votes) 0 comments   /   posted by Silverlight Show on Nov 29, 2011 Tags:   windows-phone , mango , jeff-fansler Read original post by Jeff Fansler at BlankenBlog […]

  3. […] Esta es una traducción de Day 28: Media Library, puedes encontrar el artículo aquí en su versión… […]

  4. Thuan Avatar

    Thank you! You do use the MediaElement control to play next to each item in the list

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 )

Facebook photo

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

Connecting to %s

Create a website or blog at WordPress.com

%d bloggers like this: