Search code examples
c#mediaelementpixelsensesoundeffect

C# Surface (WPF) / Soundeffects -> Dictionary<String,MediaElement>


due to the lack of Sound Effects in Microsoft Surface Applications I tried to built a "Sound bank" with sound files (.wav) in a Dictionary.

The sound file is short.

path = PathToFile

My "Sound bank":

Dictionary<string, MediaElement> soundBank = new Dictionary<string, MediaElement>(29);
soundBank = new Dictionary<string, MediaElement>(20);
        soundBank.Add("1", new MediaElement());
        soundBank.Add("2", new MediaElement());
        soundBank.Add("3", new MediaElement());
        soundBank.Add("4", new MediaElement());
        soundBank.Add("A", new MediaElement());
        soundBank.Add("BE", new MediaElement());
        soundBank.Add("CF", new MediaElement());
...

foreach (var item in soundBank)
        {
            Console.WriteLine(item.Key);
            //soundBank[item.Key] = new MediaElement();
            soundBank[item.Key].Source = new Uri(path);
            soundBank[item.Key].LoadedBehavior = MediaState.Manual;
            soundBank[item.Key].UnloadedBehavior = MediaState.Manual;
            soundBank[item.Key].Volume = 1;
            soundBank[item.Key].MediaEnded += new System.Windows.RoutedEventHandler(mp_MediaEnded);

If I try to play multiple sounds (on_button_click) the sounds are delayed or simply do not play:

public void play(string key)
    {

        soundBank[key].Stop();
        soundBank[key].Play();

    }
    void mp_MediaEnded(object sender, System.Windows.RoutedEventArgs e)
    {
        ((MediaElement)e.Source).Stop();
    }

SoundPlayer and MediaPlayer are not suited, because they stop all other played sounds.


Solution

  • I'm using the irrKlang library now for my project:

    It is very very easy to use:

    using IrrKlang;
    ...
    
    ISoundEngine engine = new ISoundEngine();
    
    ...
    
    engine.Play2D(@"C:\Users\Public\Documents\sound.wav");
    

    Ultimately simple solution ^^