Question

Can anyone tell me the best approach to playing single-tone, audio (.mp3) files in a Windows Phone 8 app? Think of a piano app, where each key would represent a button, and each button would play a different tone.

I'm looking for the most efficient way to go about this - I've got 8 different buttons that need to play a different tone when tapped.

I tried using the MediaElement:

MediaElement me;

public MainPage()
{
    InitializeComponent();

    me = new MediaElement();
    me.AutoPlay = false;
    me.Source = new Uri("/Sounds/Sound1.mp3", UriKind.Relative);

    btnPlay.Click += btnPlay_Click;

}

private void btnPlay_Click(object sender, EventArgs e)
{
    me.Play();
}

But nothing happens, either in the emulator or on a device (testing w/ a Lumia 822). Am I doing something wrong here? It seems like it should be pretty simple. Or would using MediaElement even be the best thing to use for my scenario?

Would this fall under the Background Audio category? I've read through this example but it seems overkill for what I want to do.

I've also read about using XNA's SoundEffect to do the job, but then I'd have to convert my .mp3 files to .wav (which isn't necessarily a problem, but I'd rather not go through that if I don't need to).

Can anyone tell me either what I'm doing wrong in my example above or guide me to a better solution for playing quick <1s audio tones?

Was it helpful?

Solution

I had this problem before with MediaElement not playing audio files. After many attempts I found out that it only plays if it defined in the xaml and AutoPlay is set to true.

Try defining it in the xaml or you can just add it to your LayoutRoot.

  var me = new MediaElement();
  LayoutRoot.Children.Add(me);
  me.AutoPlay = true;
  me.Source = new Uri("Sound/1.mp3", UriKind.Relative);

OTHER TIPS

I have had good luck just doing this piece of code in my app. But it may not work as well in your context, give it a whirl though.

mediaElement.Source = new Uri("/Audio/" + songID.ToString() + ".mp3", UriKind.Relative); mediaElement.Play();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top