Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a sound in NETCore?

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 ?

like image 866
dbraillon Avatar asked Mar 16 '17 21:03

dbraillon


People also ask

Does .NET Core use Mono?

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.

What is the difference between mono and .NET Core?

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 .

Can you use C# in core?

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.


2 Answers

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.

like image 79
joshcomley Avatar answered Sep 21 '22 05:09

joshcomley


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.

like image 28
dbraillon Avatar answered Sep 24 '22 05:09

dbraillon