i'm working on a project in which sounds (.wav-files) should be played when some actions happen. The files are on the local drive in a subfolder of the project/location.
For playing the sounds synchronously one after another I have the following class:
public class Player
{
private readonly BlockingCollection<Sound> _queue;
public Player()
{
_queue = new BlockingCollection<Sound>();
Task.Factory.StartNew(Play);
}
public void PlaySound(Sound sound)
{
_queue.Add(sound);
}
private void Play()
{
foreach (var sound in _queue.GetConsumingEnumerable())
{
var filename = GetFile(sound);
using (var player = new System.Media.SoundPlayer(filename))
{
player.PlaySync();
}
}
}
}
The problem I encounter sometimes is, that the PlaySync method runs for over a minute until the sound is played. The soundfiles have a duration of 0,2 seconds. This only happens on the first call of the method. I tried laoding the files into memory and call the Load/LoadAsync method of the SoundPlayer class. This has no effect on the situation. The PlaySync-call sometimes need more than a minute.
I tried also the System.Windows.Media.MediaPlayer class but it looks to me that this class can only play sounds asynchronous and I need the sounds synchronous. The events like MediaEnded on this class are never called.
I tried for many days now to find a solution for this problem but didn't find anything. Could anyone help me?
I'm using WPF with the MVVM framework Prism and this class is instantiated inside a viewmodel.