Skip to content

Instantly share code, notes, and snippets.

@jtbrower
Created September 25, 2020 16:23
Show Gist options
  • Save jtbrower/e59cc97ab62bc319ae29e91330da25f6 to your computer and use it in GitHub Desktop.
Save jtbrower/e59cc97ab62bc319ae29e91330da25f6 to your computer and use it in GitHub Desktop.
Play a Sound Wave File in .Net, NetCore and Net5.0 without additional Media Libraries
namespace Gist
{
using System.Runtime.InteropServices;
//NOTICE : Applicable only to Windows and wav files
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// A class that uses PInvoke to play a wave file in DotNet Core, .Net and Net5.0. This function
/// will not work on non Windows platforms, but does work on alternative UI frameworks such as
/// Avalonia.
/// </summary>
////////////////////////////////////////////////////////////////////////////////////////////////////
public static class SimpleSoundPlayer
{
//See the following links for more information.
// https://docs.microsoft.com/en-us/previous-versions/dd743680(v=vs.85)
// https://docs.microsoft.com/en-us/windows/win32/multimedia/the-playsound-function
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interop/how-to-use-platform-invoke-to-play-a-wave-file
// When playing a simple sound, the developer doesn't want a complex library. Frameworks such
// as WPF and WinForms require access to specific Media libraries that are not available in
// frameworks such as Avalonia. This approach to playing a wav file works in full .Net
// Framework as well as DotNet Core/Net5.0.
public static bool PlaySoundWaveFileAsync(string fullOrRelativePathToWaveFile)
{
return PlaySound(fullOrRelativePathToWaveFile, new System.IntPtr(), PlaySoundFlags.SND_ASYNC);
}
[DllImport("winmm.DLL", EntryPoint = "PlaySound", SetLastError = true, CharSet = CharSet.Unicode, ThrowOnUnmappableChar = true)]
private static extern bool PlaySound(string szSound, System.IntPtr hMod, PlaySoundFlags flags);
[System.Flags]
private enum PlaySoundFlags : int
{
SND_SYNC = 0x0000,
SND_ASYNC = 0x0001,
SND_NODEFAULT = 0x0002,
SND_LOOP = 0x0008,
SND_NOSTOP = 0x0010,
SND_NOWAIT = 0x00002000,
SND_FILENAME = 0x00020000,
SND_RESOURCE = 0x00040004
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment