How to play sound in NETCore?

I am trying to play sound inside an .Net Core console application and I cannot figure it out.

I am looking for something controlled inside a .Net Core environment, perhaps like a regular .Net:

// Not working on .Net Core System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav"); player.Play(); 

A problem has been discovered with the Gnetub kernel in dotnet, where they talk about it.

https://github.com/dotnet/core/issues/74

They say that there is no high-level API for playing sound, but the problem is 9 months old, so I hope there is something new?

+9
source share
3 answers

Now there is a way to do this with the NAudio library (starting from 1.9.0-preview1 ), but it will only work on Windows.

So, using NAudio, here is the code for playing sound in .NET Core, if 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 choose @Fiodar, which uses Node.js.

+1
source

As a workaround until .NET Core gets sound support, you can try something like this:

 public static void PlaySound(string file) { Process.Start(@"powershell", $@ "-c (New-Object Media.SoundPlayer '{file}').PlaySync();"); } 

Of course, this will only work with Windows with PowerShell installed , but you can determine which OS you are on and act accordingly.

+1
source

There is a platform independent way to do this. In fact, all the sound functionality available in the .NET Framework was Windows-specific; therefore, none of them turned into .NET Core.

However, the good news is that Node.js has countless libraries that can play sound across different systems, and there is a library available for ASP.NET Core that can directly reference Node.js code. It is called NodeServices. Don't be distracted by the fact that it is available only for ASP.NET Core. In fact, ASP.NET Core, unlike the version of the ASP.NET.NET Framework, is nothing more than a thin layer of web hosting features that runs on top of a standard console application. You do not need to use it as a web application, but it will provide you with many useful extras, such as an easy-to-use dependency injection library.

More details

This article describes how NodeServices works. It is really straight forward.

+1
source

Source: https://habr.com/ru/post/1265579/


All Articles