Share via


Play Audio in Windows Phone Application

There are a few options to play audio in windows phone application which I tried and worked:
 
1. Use XNA Library to Play a Wave Sound
Add Microsoft.Xna.Framework.dll to yourphone application project, and
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
 
Than you can use the following code snippet to play a sound (don’t forget to add the sound file into your project’s Sound folder)
 
string dingSoundFile = "Sound/Ding.wav";
var stream = TitleContainer.OpenStream(dingSoundFile);
if (stream != null)
{
      var effect = SoundEffect.FromStream(stream);
      FrameworkDispatcher.Update();
      effect.Play();

}
 
Or
 
string dingSoundFile = "Sound/Ding.wav";
SoundEffectAction soundEffect = new SoundEffectAction();
soundEffect.Source = dingSoundFile;
soundEffect.Play();
 
 
2. Use MediaElement to Play MP3
In xaml, use a media element. If you set AutoPlay="True", it will just play when the page loads:
<MediaElement Source="Sound/Sleep Away.mp3" AutoPlay="True"/>
 
If you don’t specify a Source in the xaml, you can use a play button to start the play:
 
<MediaElement x:Name="MediaElement1" AutoPlay="False" MediaOpened="MediaElement_MediaOpened"/>
private void Play_Click(object sender, RoutedEventArgs e)
{
      MediaElement1.Source = new Uri("Sound/Sleep Away.mp3", UriKind.Relative);
      MediaElement1.Position = new TimeSpan(0);
 }
 
 private void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
 {

      MediaElement1.Play();
 }
 
private void Pause_Click(object sender, RoutedEventArgs e)
{
     MediaElement1.Pause();
 }
 
3. Play Background Audio
 
You may want your Windows Phone application continues playing audio even when the application is no longer in the foreground. This can be achieved by implementing an audio playback agent. Refer to https://msdn.microsoft.com/en-us/library/hh202978(v=VS.92).aspx for details

4. Play Audio by Implementing TargetedTriggerAction
 
Refer to https://www.japf.fr/2010/08/sound-effect-in-wp7-sl-application/ for details

Comments

  • Anonymous
    February 03, 2013
    nice but how to add thumbnail image to media element?