Jouer un son en silverlight sur windows phone 7

Avant toute chose, il faut importer le FrameWork XNA audio

using Microsoft.Xna.Framework.Audio;

Dans mon cas, j’ai utilisé le SoundEffect pour récupérer et exécuter le son. Je déclare donc mon son

 private SoundEffect monSon;

Ensuite, dans le constructeur de ma page, je vais Load mon son dans la variable que j’ai créé. Mon son se trouve dans un dossier Sounds que j’ai créé.

LoadSound("Sounds/monSon.wav", out monSon);

Pour pouvoit utiliser le LoadSound, voici la méthode qui est a créé

// //Loads a wav file into an XNA Framework SoundEffect. // //Relative path to the wav file. //The SoundEffect to load the audio into. private void LoadSound(String SoundFilePath, out SoundEffect Sound) { // For error checking, assume we'll fail to load the file. Sound = null; try { // Holds informations about a file stream. StreamResourceInfo SoundFileInfo = App.GetResourceStream( new Uri(SoundFilePath, UriKind.Relative)); // Create the SoundEffect from the Stream Sound = SoundEffect.FromStream(SoundFileInfo.Stream); } catch (NullReferenceException) { // Display an error message MessageBox.Show("Couldn't load sound " + SoundFilePath); } }

Ensuite, dans votre constructeur, vu qu’on travaille avec le framework XNA, il faut simuler la boucle du xna. On réalise ceci de la manière suivante :

 // Timer to simulate the XNA game loop (SoundEffect classes are from the XNA Framework) DispatcherTimer XnaDispatchTimer = new DispatcherTimer(); XnaDispatchTimer.Interval = TimeSpan.FromMilliseconds(50); // Call FrameworkDispatcher.Update to update the XNA Framework internals. XnaDispatchTimer.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } }; // Start the DispatchTimer running. XnaDispatchTimer.Start();

Voila, il ne vous reste plus qu’a lancer votre son ou vous le voulez, dans cet exemple, je le mets sur le click d’un bouton

 private void button1_Click(object sender, RoutedEventArgs e) { monSon.Play(); }

Now, enjoy !

No Comments

Post a Comment