Thursday, June 10, 2010

Playing MP3 - Files

In the post Playing Wave Files I described, how to play Wave - Files with C#. Now I want to show how to play MP3 - files.
Due to the compressed format this is a bit more complicated, there is no direct "easy" command to play an MP3 - file, but still there are many possibilites.
On the one hand MP3 - files can be played via the API - function MCISendString(), but in my opinion the code is cumbersome and not easy to understand.
A very easy naive variant is to give System.Diagnostics.ProcessStart() the MP3 - file as parameter, the operating system then will open and play the file with the standard player:

System.Diagnostics.Process.Start(@"C:\Dokumente und Einstellungen\Oliver\Eigene Dateien\Eigene Musik\101-darius_and_finlay_and_shaun_baker_-_show_me_10_(dj_gollum_edit).mp3");
 Allowedly, this method is not very elegant.
Therefor I want to show you today how to include the Windows Media Player control, with which MP3 files and most other audio formats can be played.
The control can be added to the toolbox by right clicking on this and then selecting Select element .... In the opening window then switch to COM - controls and select Windows Meida Player.
This can now be placed like a button on the form.
If the player is just used for playing audio files, the property Visible can be set to false, so it is not visible on the form.
With the property URL the file to be played can be selected. Normally, the player then directly starts with playing the file.
With the property Ctlcontrols we can access the loaded data of the player, the functions start() and stop() serve the purpose of starting and stopping the playing manually.
Over settings some properties of the player, like the volume, can be modified.
In the following example an MP3 - file is loaded, the playing is stoppend and the application waits for 2 seconds. Afterwards, the player is set to full volume and the playing is continued:
Danach wird der Player auf volle Lautstärke gestellt und die Datei abgespielt:

axWindowsMediaPlayer1.URL = @"C:\Dokumente und Einstellungen\Oliver\Eigene Dateien\Eigene Musik\101-darius_and_finlay_and_shaun_baker_-_show_me_10_(dj_gollum_edit).mp3";
axWindowsMediaPlayer1.settings.volume = 100; // 0 = no sound, 100 = full volume;

No comments:

Post a Comment