Friday, March 22, 2013

How to add songs to the emulator's MediaLibrary

    One of the new features of the Windows Phone 8 SDK is the ability to save(add) songs to the phone's MediaLibrary. This is a really nice when you add songs to the MediaLibrary any other music application that you have installed on your phone can play the songs that your application has saved.. The SaveSong method is found in the MediaLibraryExtensions class. Here are the parameters of this method:


public static Song SaveSong (
         MediaLibrary library,
         Uri filename,
         SongMetadata songMetadata,
         SaveSongOperation operation

    The method requires the ID_CAP_MEDIALIB_AUDIO capability and will return a reference to the newly saved song. One of the things that the documentation forgot to mention is that the filename Uri has to be an Uri to a file on the IsolatedStorage. You cannot give a direct Uri to an asset file (this I think because using the SaveSongParameter you can choose if you want to copy or move the file to the MediaLibrary) as you will get InvalidOperationException. If you want to add a song deployed as an asset you will first have to copy the file to the IsolatedStorage and then save it to the MediaLibrary.

    To copy the file to the IsolatedStorage you can use the:
 var resource = Application.GetResourceStream(new Uri(@"Assets/Songs/"+fileName, UriKind.Relative));  
 resource.Stream.CopyTo(fileStream, 4096);  

or you can use the WinRT Api to read the asset file:
  songUri=new Uri("ms-appx:///Assets/Songs/"+fileName,UriKind.Absolute);  
  var file=await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(songUri);  

    One interesting parameter is the SongMetadata. This enables you to "mess" with the metadata that will be saved to the MediaLibrary. If this parameter is null then the function will automatically import the file's metadata. If you still want to verify/import just some of the files metadata you can use the PCL ID3.NET and read the metadata of the file you have on the Isolated Storage. The portble dll is Id3.dll. You just have to pass the Stream to the Mp3Stream method:

 Id3.Mp3Stream mp3 = new Id3.Mp3Stream(resource.Stream);  
 if (mp3.HasTags)  


No comments:

Post a Comment