I'm trying to play a sound inside a .Net Core console application and I can't figure this out.
I am looking for something managed inside the .Net Core environment, maybe like regular .Net :
// Not working on .Net Core
System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav");
player.Play();
Found an issue on dotnet core Github where they talk about it.
https://github.com/dotnet/core/issues/74
They say there is no high-level API for audio playback but the issue is 9 months old, so I hope there is something new ?
There is now a way to do it with NAudio library (since 1.9.0-preview1) but it will only works on Windows.
So using NAudio, here the code to play a sound in .NET Core assuming you are doing it from a Windows environment.
using (var waveOut = new WaveOutEvent())
using (var wavReader = new WavFileReader(@"c:\mywavfile.wav"))
{
waveOut.Init(wavReader);
waveOut.Play();
}
For a more global solution, you should go for @Fiodar's one taking advantage of Node.js.
As a workaround until .NET Core has audio support, you could try something like this:
public static void PlaySound(string file)
{
Process.Start(@"powershell", $@"-c (New-Object Media.SoundPlayer '{file}').PlaySync();");
}
Of course this would only work on Windows with PowerShell installed, but you could detect which OS you are on and act accordingly.
There is a platform-independent way of doing it. Essentially, all of the sound-playing functionality that was available in .NET Framework was Windows-specific; therefore none of it made it into .NET Core.
However, the good news is that Node.js has countless libraries that can play sound on various systems and there is a library available for ASP.NET Core which can talk to Node.js code directly. It's called NodeServices. Don't be put off by the fact that it's only available on ASP.NET Core. Essentially, ASP.NET Core, unlike the .NET Framework version of ASP.NET, is nothing more than a thin layer of web hosting functionality running on top of a standard console app. You don't necessarily have to use it as a web app, but it will provide you with many useful extras, such as an easy to use dependency injection library.
More
This article describes how NodeServices work. It is really straight-forward.