[Sample] Playing with music file

原创 2003年02月01日 15:26:00

Getting into My Music

If you decide to have your own interface for playing music, one of the fundamental decisions is how to manage your library of MP3/WMA files. Do you use the existing library of another program (such as Microsoft?Windows Media?Player), or do you write your own? This is not a particularly easy decision, and I am still not completely sure which is the best choice, but I had to make a decision or I would never be able to move on in my development. I decided that using a database to create my own library/catalog of music files would be the most flexible option, although this path would likely require more work at the beginning. I set up a new database in MSDE on my development machine, and created the following schema (actually it is a fair bit more complicated, but these are the key tables):

Click here for larger image.

Figure 1. A simple database schema for holding my music library

Of course, after building my own system, along came what is arguably a much better one in the form of Windows XP Media Center Edition, which created a bit of a conflict in my mind. Why continue building my own if I could go get a better one that is completely done for me? The confusion only lasted a few moments though; I am a programmer, so I often build things when it would be much more logical to buy them.

Reading the Tags

Although I didn't have any formal requirements or architectural documentation (maybe it's just me, but having to produce all the same documentation as a work project would take some of the fun out of it), I knew that moving to the next stage would require code that could read all of the attributes from an audio file梐rtist, song, and album names, for example.

I originally assumed my collection would be in MP3 files, which store attributes using various flavors of a system called "ID3," so using the resources available at www.id3.org, I started creating a Microsoft Windows .NET Framework-based library that could handle the more common versions of ID3 tags. In parallel, I began ripping my CD collection onto my hard drive (for my own personal use, of course). For this, I used Windows Media Player, and I spent some time investigating the various options available in terms of WMA (Windows Media Audio) versus MP3 and different encoding rates.

Note   Choosing a format and encoding quality requires some research, especially before you rip several hundred CDs to your hard drive. (That is not a task I would like to redo.) I won't spent a lot of time explaining why I chose WMA. I am not really an objective reviewer of audio file formats anyway, but it appears to produce higher quality at lower file sizes, which seems like a good thing to me. Starting with version 9 of Windows Media Player, a variable bit rate (VBR) encoding format is available, which might turn out to be the best choice, but I didn't have access to that format when I was ripping my collection to disk.

I ended up choosing WMA at around 160 kilobits per second (Kbps). Now I needed to make sure my attribute reading code could handle both WMA and MP3 files. Well, to make a long story somewhat shorter, I decided that since Windows Media Player could handle both file formats, I should take a look at the Windows Media SDK. Sure enough, the SDK even provided a sample to do exactly what I wanted. Instead of doing all my work for me and writing the sample as a COM component, however, it was a regular old console application.

I started trying to modify their wonderful C++ code to create a nice friendly component, but it was 3 A.M. and my patience was not up to the challenge. So (in a trend that continues across most of my hobby programming), I cheated and took the quick and dirty way out. I modified their code slightly to handle a larger list of MP3 and WMA tags, and to output the information (to the console still) as XML. With these changes in place, I wrapped the component up into a couple of Framework functions, essentially just calling it with a command-line parameter of the path to my audio file, and retrieving its output back as a nice XML document. Very cheesy, but at 3 A.M. I just wanted to get something working, and this works just fine.

Note   The code for the XML generating console application is almost 100 percent identical to the sample in the Windows Media SDK, but the exe is provided for you as part of the code download for this article. I've also included a sample bit of Framework code to call the console application and process its output, so that you can play around with your own MP3 and WMA files.

Using this program from the command line is fairly simple. You just specify the name of the file you want to have it scan. There are no options for multiple files, although that would likely be an excellent addition. Running this program against the WMA file of "Sophia's Pipes" by Ashley MacIssac produces this output to the console:

Although this isn't the prettiest XML, it is valid, and therefore it is easy to read using the System.XML classes in the Framework. Running the console application and grabbing the output is made possible through the System.Diagnostics namespace and the Process and ProcessStartInfo classes.

Loading the XML

I do a quick little replace to make sure that any "&" characters in the music file tags are interpreted correctly by the XML classes. Then I load this XML in as a new XMLDocument.

Once I have the XMLDocument, I create a new instance of a class (MusicFileInfo) to hold the attributes of the file and fill in the appropriate properties. The complete function that takes a filename and returns an instance of MusicFileInfo is provided below.

In addition to creating the MusicFileInfo class, I also used the Collection Generator tool from GotDotNet to create a strongly typed collection of MusicFileInfo objects. As I scan in music files, I add their information to this collection and then, because it is a strongly typed collection, I can use it to data bind a grid control.

The final sample application (included in the download for this column) produces the results shown in Figure 2.

Figure 2. The demo MusicFileTags application displays the tags of any WMA/MP3 files you select.

Obsolete Already

It is nice to have code finished and working, but things keep changing in the world of computers, and new options often present themselves just after you have finished your solution. Early this month, January 2003, Microsoft released a new version of Windows Media Player (available from http://www.windowsmedia.com/9series/download/download.asp) and a new version of the Windows Media Format SDK (available from http://msdn.microsoft.com/downloads/list/winmedia.asp). Once I downloaded the new player and the new SDK, I found something wonderful: managed code samples for reading music file attributes. My current solution, reading XML output from a console application, works for me (and in fact I haven't replaced it yet) but the managed code option is much more appealing. The nature of strings, special characters (&, <, >, and so on), and XML means that the original system works for all my current music. Nevertheless, I expect it will eventually find some artist, album, or song name it cannot process successfully. Using a managed-code solution avoids those issues, and also allows for structured error handling (among other benefits).

Included in the SDK's managed code samples is a simple wrapper library, which encapsulates the underlying Windows Media calls in C# code. This wrapper makes it much easier to use those calls from a Microsoft Windows .NET Framework-based application. I have included only the compiled version of that library (in the bin directory of my sample project), but you can get the complete source code by downloading the Format SDK for yourself. Now that all of the Windows Media calls are handled by this wrapper library, the next step is to create a simple class that accepts the file path for a WMA file and retrieves all of the available attributes.

Note   Reading through this code (and the full code available in the download), you will find quite a few conversions between unsigned integers (UInt16, UInt32, and UInt64) and signed integers (Integer/Int32, Long/Int64). The wrapper supplied with the SDK is not CLS-compliant, which means it is not easy to use from outside of C#. I could have just used C# to write my new application, but I almost always use Microsoft?Visual Basic?.NET, and it was worth a little bit of extra code to stay within my language of choice. Note that, in most cases, these conversions could be done within the wrapper itself, ensuring that it was CLS-compliant and easy to use from any Framework language.

As you can see, the availability of the managed code wrapper makes it very easy to use the Windows Media libraries from the Framework. In time I will rewrite my music system to use this wrapper for reading file attributes, but for now I have just created a version of the first sample that uses the new managed wrapper. Other than the actual attribute reading code, the rest of the application is unchanged.

Coding Challenge

At the end of some of my Coding4Fun columns, I will have a little coding challenge梥omething for you to work on if you are interested. For this first article, the challenge is to build your own application that loads and uses MP3/WMA attributes (using my sample as a starting point if you wish). Try to create an application that uses these attributes in some interesting and/or useful way, or create your own code for loading the attributes as an alternative to using the Windows Media libraries. Of course, Framework code is preferred (Visual Basic .NET, C#, or Managed C++ please), but an unmanaged component that exposes a COM interface would also be good.

Just post whatever you produce to the User Samples area of GotDotNet and send me an e-mail message (at duncanma@microsoft.com) with an explanation of what you have done and why you feel it is interesting. I'd appreciate it if you would include a quick blurb on yourself as well, so that I can tell the world about you if I pick your code to mention in an article. Sorry, there are no prizes, but I will respond to the most interesting code I receive, and you will gain the respect and admiration of your peers by posting onto GotDotNet. As far as other submission guidelines, I will follow the rules set forth on the GotDotNet site as our terms of use for your code. (You will need to logon with your Microsoft?Passport credentials to view the upload agreement.) You can send in submissions whenever you like (but always through GotDotNet's upload system please; I don't want my inbox to fill up with code samples!). I am always interested in seeing what code programmers create when they aren't being paid. On that note, check out this cool Framework game Miner Arena, written by some programmers at the Budapest University of Technology and Economics in Hungary. The setup of Miner Arena isn't exactly simple, but the depth of code and architecture explored in this game makes it worth digging into.


If you want to build your own music playing system, then you need to be able to read the attributes of your music files, as demonstrated in the code for this article. In future articles, I will continue with the music player examples, but I will also cover a few other topics, such as games, graphics, network communication, and more. Have your own ideas for hobbyist content? Let me know at duncanma@microsoft.com, and happy coding!



Duncan Mackenzie is the Microsoft Visual Basic .NET Content Strategist for MSDN during the day, and a dedicated coder late at night. It has been suggested that he wouldn't be able to do any work at all without his Earl Grey tea, but let's hope we never have to find out. For more on Duncan, see his profile on GotDotNet.

HDU 1988 Cube Stacking (数据结构-并查集)

HDU 1988 Cube Stacking (数据结构-并查集) 题目大意: 有N个立方体和N个格子,1~N编号,一开始i立方体在i号格子上,每个格子刚好1个立方体。现在m组操作,M a b表示将...
  • a1061747415
  • a1061747415
  • 2014年07月30日 11:42
  • 1473


一 src中的最后一个文件报错,在package的第一个字母都报错,所有导入的android的包都报错 原因:文件project.properties 配置错误 打开项目根目录下的文件project....
  • lllkey
  • lllkey
  • 2014年12月23日 13:43
  • 6486

[gdebi命令]解决netease music无法播放歌单问题

在ubuntu 16.04 LTS中通过apt-get安装了网易云客户端,结果出现能播放MV,不能播放歌单的情况. 1.由于网易云客户端已经启动,以致起始并未注意到是某些依赖库未安装: x...
  • u013398960
  • u013398960
  • 2016年11月07日 22:44
  • 1347

Gaplessly playing large audio file with MS wave I/O functions

From: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=4422&lngWId=3 Windo...
  • chaosllgao
  • chaosllgao
  • 2012年07月27日 17:23
  • 1084

FOJ Playing with Calculator (模运算)

Problem Description Pete is playing a game. He types on a calculator a natural number K and then ...
  • ShiWaiGaoRen12345
  • ShiWaiGaoRen12345
  • 2016年08月15日 22:12
  • 146

527A. Playing with Paper【math】

A. Playing with Paper time limit per test 2 seconds memory limit per test 256 megabytes i...
  • u014787301
  • u014787301
  • 2015年03月21日 18:33
  • 509

Playing with ptrace, Part I

Nov 01, 2002  By Pradeep Padala  in SysAdmin Using ptrace allows you to set up system call ...
  • starstarstone
  • starstarstone
  • 2012年04月26日 11:10
  • 345

programming-challenges Playing with Wheels (110902) 题解

一开始居然没想到bfs。 #include #include #include #include #include #include #include #include #inclu...
  • houhouzhe
  • houhouzhe
  • 2015年11月03日 22:59
  • 255

Playing with huge information streams: Twitter Storm!

Past Christmas I found the perfect pet project for that season: Twitter Storm. Basically is a e...
  • macyang
  • macyang
  • 2012年02月06日 21:24
  • 976

Playing with Virtual Memory

文章来源:http://www.snailinaturtleneck.com/blog/2011/08/30/playing-with-virtual-memory/  很赞的一篇文章! Whe...
  • macyang
  • macyang
  • 2011年09月01日 22:43
  • 790
您举报文章:[Sample] Playing with music file