There is a
System.Media.SoundPlayer
class that plays sound files or streams.
It is part of
System.dll
under .NET FrameWork (no extra reference needed); it has been moved to
System.Windows.Extensions.dll
under .NET 6 (which needs you to add a reference).
ADDED:
you can also use P/Invoke to call on the native method
sndPlaySound
inside winmm.dll
The code below should give you a starting point, I use it for playing sounds from embedded resources:
public static void PlaySound_old(Type type, string resourceName) {
try {
if (type == null) type = typeof(LP_Resource);
resourceName = type.Namespace + ".resources." + resourceName;
Stream stream = type.Assembly.GetManifestResourceStream(resourceName);
int len = (int)stream.Length;
byte[] buf = new byte[len];
stream.Read(buf, 0, len);
GCHandle handle = GCHandle.Alloc(buf);
IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buf, 0);
int res = sndPlaySound(ptr, 4);
handle.Free();
log("Played sound " + resourceName);
} catch (Exception e) {
log(resourceName + " failed: " + e.Message);
}
}
[DllImport("Winmm.dll", CharSet = CharSet.Unicode,
CallingConvention = CallingConvention.StdCall)]
internal static extern int sndPlaySound(IntPtr buffer, int dwFlags);
Alas, that too only handles .wav sounds.
ADDED2:
the only way I've found so far to play MP3 from C# is using WMPLib:
WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer();
player.URL = absoluteFilePath;
player.controls.play();
which needs an absolute file path (like C:\...\filename.mp3) or an actual URL.
I see no way to play a sound resource, without temporarily creating a file that is.
In order to use WMPLib, one has to add a reference:
- references
- add reference
- COM
- search "Windows Media Player", the tooltip should mention C:\WINDOWS\system32\wmp.dll
:)