Digital Ape
Digital Ape

Reputation: 21

Threading issue with MediaPlayer C#

I am creating an app that has an 9x9 multidimensional array full of custom objects, and when a button is pressed a sound specific to every single object needs to be played.

I run this method to load the sound, runs with no known problems:

   public void setSoundToPlay()
    {
        OpenFileDialog openFileDiag = new OpenFileDialog();
        if ((bool)openFileDiag.ShowDialog())
        {
            audio = new MediaPlayer();
            audio.Open(new System.Uri(openFileDiag.FileName));
        }

    }

but when I activate another method to play sound:

    public void buttonActivated()
    {
                audio.Play();
    }

I get a System.InvalidOperationException:{"The calling thread cannot access this object because a different thread owns it."}

The object running the mediaplayer object is nested within another object, is that the problem. I tried understanding threading but have made no headway.

I also need to, in some cases, need to have all the sounds be able to play at once. Is this the best object for the job?

Upvotes: 0

Views: 1636

Answers (2)

Jorge Gonzales
Jorge Gonzales

Reputation: 71

Use the Dispatcher property associated with the media player element, like this

 public void buttonActivated()
 { 
   audio.Dispatcher.Invoke(() =>
            {
                audio.Play();
            });
 }

Upvotes: 2

Digital Ape
Digital Ape

Reputation: 21

To access devices like this from other methods use

Application.Current.Dispatcher.BeginInvoke(new Action(() => objectName);

Upvotes: 0

Related Questions