Share via


how to play MP3 files in C#

Question

Monday, March 4, 2019 4:41 PM

I've got a bunch of MP3s for a project and I want to hear them in the app I'm working on.  There are a few posts about the WMPLib but I can't seem to download the Windows Media Player SDK anywhere...  

how can I play MP3s in C#2019?

BadButBit

my code is perfect until i don't find a bug

All replies (6)

Wednesday, March 6, 2019 7:00 PM ✅Answered

For example, minimum code with MCI :

StringBuilder sb = new StringBuilder();
string sFileName = @"E:\01. IMANY - Don't Be so Shy (Filatov & Karas Remix).mp3";
string sAliasName ="MP3";
int nRet = mciSendString("open \"" + sFileName + "\" alias " + sAliasName, sb, 0, IntPtr.Zero);
nRet = mciSendString("play " + sAliasName, sb, 0, IntPtr.Zero);

Wednesday, March 6, 2019 7:45 PM ✅Answered

did I mention I'm working in C# 2019(preview)?

because I cut'n'paste'd what you suggest and it got angry with me.

is it some setting of my IDE that's off?

BadButBit

my code is perfect until i don't find a bug


Wednesday, March 6, 2019 8:02 PM ✅Answered

The tooltip on DllImport should say to add :

using System.Runtime.InteropServices;

at beginning...


Monday, March 4, 2019 4:50 PM

You don't need to download anything

Using the Windows Media Player Control in a .NET Framework Solution

or you can use DirectShow or mciSendString (P/Invoke) with open then play commands, among other methods.

Declaration for mciSendString :

[DllImport("Winmm.dll", SetLastError = true)]
static extern int mciSendString(string lpszCommand, [MarshalAs(UnmanagedType.LPStr)] StringBuilder lpszReturnString, int cchReturn, IntPtr hwndCallback);

Wednesday, March 6, 2019 5:53 PM

thanks for your reply, but I'm not familiar with these MCI and looking at the MCI documentation doesn't really help me get started.  could you give me an example of how to load and play a file?

e.g.

public void playAudio(string strAudioFilename)
{
    if (strAudioFilename == null) return;

    WMPLib.WindowsMediaPlayer Player;
    WMPLib.WindowsMediaPlayer winmp = new WMPLib.WindowsMediaPlayer();
    wmp.URL = strAudioFilename;
    wmp.controls.play();
}

like the easy-ways when this used to work?

my code is perfect until i don't find a bug


Thursday, March 7, 2019 5:41 AM

Also MediaPlayer is very simple (references to PresentationCore and WindowsBase ) :

// Global
private MediaPlayer mediaPlayer = new MediaPlayer();

// In a button click for example
string sFileName = @"E:\01. IMANY - Don't Be so Shy (Filatov & Karas Remix).mp3";
mediaPlayer.Open(new Uri(sFileName));
mediaPlayer.Play();