Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to play sound in Windows 8

Tags:

windows-8

I want to play sound from a mp3 file in windows 8 metro-style app. I tried two approaches to do so:

Method1:
This is using the code provided by https://stackoverflow.com/a/10961201/147530. It works.

Method 2:
Here I just new a MediaElement and set its Source property like so:

var x = new MediaElement { Source = new Uri("ms-appx:/Assets/MyMp3File.mp3") };  

When I do x.Play() nothing happens however. There are no exceptions thrown.

Question: How can I make method 2 work?

EDIT: Wanted to update that none of the MediaFailed, MediaOpened, MediaEnded event handlers get called using Method 2.

sound = new MediaElement { Source = new Uri("ms-appx:/Assets/Clook.mp3") };
                    sound.MediaFailed += sound_MediaFailed;
                    sound.MediaOpened += sound_MediaOpened;
                    sound.MediaEnded += sound_MediaEnded;

static void sound_MediaEnded(object sender, RoutedEventArgs e)
        {
            Debugger.Break();
        }

        static void sound_MediaOpened(object sender, RoutedEventArgs e)
        {
            Debugger.Break();
        }

        static void sound_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            Debugger.Break();
        }
like image 969
morpheus Avatar asked Feb 21 '23 05:02

morpheus


2 Answers

A couple of things to try. Try the following code

var music = new MediaElement()
{
  AudioCategory = AudioCategory.ForegroundOnlyMedia,
  Source = new Uri(this.BaseUri, "Assets/MyMp3File.mp3")
};

// This is really the only difference, adding it to the visual tree
// LayoutRoot is the root of the visual tree, in the case, a grid in my XAML
LayoutRoot.Children.Add(music);

music.Play();

Adding it to the visual tree may be the key. Put a break point on that to make sure your MediaElement has data in it.

Second (and actually happened to me so, that's why I mention it), I was developing on a Samsung device from //Build that has a docking station. The audio jack on the device and the speakers are disabled when it is in the docking station. You have to plug a headset into the docking station directly or remove it from the docking station to hear any sound.

like image 69
JP Alioto Avatar answered Feb 22 '23 17:02

JP Alioto


You have to put the MediaElement in the visualTree before to make it play any media :)

like image 36
Jonathan ANTOINE Avatar answered Feb 22 '23 19:02

Jonathan ANTOINE