Search code examples
c#.net-coreaudio-player

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 ?


Solution

  • 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.