4

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();
        }
Community
  • 1
  • 1
morpheus
  • 18,676
  • 24
  • 96
  • 159
  • Have you tried: ms-appx://Assets/MyMp3File.mp3 (adding the double slash in the beginning of the uri)? – RQDQ Jun 11 '12 at 16:35
  • uri format is correct. see http://stackoverflow.com/a/9562069/147530 – morpheus Jun 11 '12 at 17:53
  • How about listening to the MediaFailed event? I was able to see an error in my environment using that. – RQDQ Jun 11 '12 at 19:04

3 Answers3

6

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.

JP Alioto
  • 44,864
  • 6
  • 88
  • 112
2

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

Jonathan ANTOINE
  • 9,021
  • 1
  • 23
  • 33
0

Use x.autoplay = true. With autoplay it will wait until it's loaded.

Sandor Drieënhuizen
  • 6,310
  • 5
  • 37
  • 80
Kaizer
  • 651
  • 3
  • 9
  • 22