Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WMPLib: player.mediaCollection.getAll().count is always 0

I am attempting to write code that reads each item from the user's Windows Media Player library. This code works for the majority of users, but for some users, getAll() will return an empty list when they clearly have hundreds or thousands of items in their Windows Media Player library.

var player = new WindowsMediaPlayer();
var collection = player.mediaCollection;
var list = collection.getAll();
int total = list.count;

I am referencing the WMPLib namespace by adding a COM reference to wmp.dll. My application ships with Interop.WMPLib.dll. How would some users' machines be configured in such a way that they run Windows Media Player with many songs in their library, but WMPLib fails to function correctly? Furthermore, what workarounds exist to reliably read the user's Windows Media Player library in all cases?

like image 513
anthony Avatar asked Mar 21 '12 20:03

anthony


1 Answers

Try this snippet and see if it works for you.

public List<MusicEntry> GetMusicLibrary()
{ 
  List<MusicEntry> entries; 
  IWMPPlaylist mediaList = null; 
  IWMPMedia mediaItem; 

  try
  { 
    // get the full audio media list 
    mediaList = media.getByAttribute("MediaType", "Audio"); 
    entries = new List<MusicEntry>(mediaList.count); 

    for (int i = 0; i < mediaList.count; i++) 
    {
      mediaItem = mediaList.get_Item(i);

      // create the new entry and populate its properties
      entry = new MusicEntry() 
      { 
        Title = GetTitle(mediaItem), 
        Album = GetAlbum(mediaItem), 
        Artist = GetArtist(mediaItem), 
        TrackNumber = GetTrackNumber(mediaItem), 
        Rating = GetRating(mediaItem), 
        FileType = GetFileType(mediaItem) 
      }; 

      entries.Add(entry); 
    } 
  } 
  finally 
  { 
    // make sure we clean up as this is COM 
    if (mediaList != null) 
    {
      mediaList.clear(); 
    } 
  } 

  return entries;
}

For more information refer to this excellent article on Code Project. http://www.codeproject.com/Articles/36338/Export-Windows-Media-Player-Music-Metadata-to-XML

like image 181
Mohib Sheth Avatar answered Oct 19 '22 18:10

Mohib Sheth