I am using Avalonia to write a very simple game featuring some short simple sounds I prefer to store in the application resources (assembly assets – I just put them in the Assets folder in the Avalonia case). After some hacking, combining parts of numerous solutions I could find on the Internet I have achieved reliable correct playback through wired earphones/speakers on Windows (didn’t even try other platforms yet) but this doesn’t work with BlueTooth earphones/speakers. Some BlueTooth devices would occasionally play a minuscule part of the sound, other just won’t play anything.
I don’t insist on using NAudio. Any other seamlessly cross-platform library which wouldn’t require the user to install additional external dependencies and which also is reasonably easy for the developer to install on Windows is acceptable. I would like the app to just work (incl. sounds) on Windows, Linux, MacOS, Android and iOS with any hardware these platforms can reasonably be expected to run on.
Below is the code demonstrating the ways I use now. I intentionally use verbose C# style avoiding most of the modern syntactic sugar for sake of better comprehensibility. I wrote these functions specifically to reproduce the problem in an isolated manner. IRL I don’t do redundant reallocation of everything every time I play a sound but the effect is the same.
Playing a standalone wav file was simple:
using NAudio.Wave;
private void PlayWaveFile(string waveFilePath)
{
using (AudioFileReader audioFileReader = new AudioFileReader(waveFilePath))
{
using (WaveOutEvent waveOutEvent = new WaveOutEvent())
{
waveOutEvent.Init(audioFileReader);
waveOutEvent.Play();
while (waveOutEvent.PlaybackState == PlaybackState.Playing)
{
Thread.Sleep(10);
}
}
}
}
Playing the same from a resource (what I am actually interested in) turnt out to be a little trickier:
private void PlayWaveResource(string waveResourceName, string assemblyName)
{
Uri uri = new($"avares://{assemblyName}/Assets/{waveResourceName}.wav");
using (Stream assetStream = AssetLoader.Open(uri))
{
using (MemoryStream memoryStream = new())
{
assetStream.CopyTo(memoryStream);
memoryStream.Seek(0, 0);
using (WaveFileReader waveFileReader = new(memoryStream))
{
using (WaveOutEvent waveOutEvent = new())
{
waveOutEvent.Init(waveFileReader);
waveOutEvent.Play();
while (waveOutEvent.PlaybackState == PlaybackState.Playing)
{
Thread.Sleep(10);
}
}
}
}
}
}
Both functions work Ok on Windows with classic wired earphones and built-in laptop speakers but fail with BlueTooth earphones/speakers.
I use NAudio 2.2.1 with Avalonia 11.0.10 and .Net SDK 8.0.205 in VisualStudio CE 2022 17.9.7 on Windows 10.0.19045 x64.