How to play a sound in NETCore?

左心房为你撑大大i 提交于 2019-12-01 03:09:57

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.

joshcomley

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.

Fiodar Sazanavets

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!