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 ?
NET Core, not mono. If you want a framework that works on Linux (x86/AMD64/ARMhf) and Windows and Mac, that has no dependencies, i.e. only static linking and no dependency on . NET, Java or Windows, use Golang instead.
NET Core and Mono? NET Core, which natively only allows you to build console apps and web applications, mono allows you to build many application types available in . NET Framework, including GUI-enabled desktop apps. So, if mono can do everything that .
Supports Multiple Languages: You can use C#, F#, and Visual Basic programming languages to develop . NET Core applications. You can use your favorite IDE, including Visual Studio 2017/2019, Visual Studio Code, Sublime Text, Vim, etc.
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 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 WaveFileReader(@"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With