When developing windows phone, sometimes we need to play the sound on some pages. There are also many playback methods:
1. Use MediaElement
2. Use SoundEffect
3. Use background playback
SoundEffect can only play files in wav format. It can play back files after the program exits. MediaElement is applicable to most cases, but cannot play back files in the background, mediaElement depends on the page and only one instance on the page can work normally.
This article describes how to use MediaElement in an application as the global player for the program and provides a help class.
Because MediaElement depends on the UI, we cannot create a MediaElement instance in ViewModel for sound playback. Therefore, we need to place MediaElement in a UI container. The following is the code of the help class:
public class GlobalPlayer{ static Popup popUp; private static MediaElement _player; public static void Play(string filePath) { popUp = new Popup(); _player = new MediaElement(); _player.Source = null; popUp.Child = _player; popUp.IsOpen = true; try { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { using (var stream = new IsolatedStorageFileStream(filePath, FileMode.Open, store)) { _player.SetSource(stream); _player.Volume = 1.0; _player.Play(); _player.MediaEnded += new RoutedEventHandler((sender, e) => { stream.Close(); stream.Dispose(); _player.Source = null; _player = null; }); _player.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>((s, args) => { stream.Close(); stream.Dispose(); _player.Source = null; _player = null; }); } } } catch (Exception) { _player.Source = null; _player = null; } } public static void StopPlay() { if (_player != null && _player.CurrentState == MediaElementState.Playing) { try { _player.Source = null; _player.Stop(); } catch (Exception) { //throw; } } }}
The usage is very simple. When we need to play the same sound on different pages, pass in the path stored in the independent space.
Updated: static constructor is used to initialize MediaElement and PopUp.
Static Player () {popUp = new Popup (); _ player = new MediaElement (); popUp. Child = _ player; popUp. IsOpen = true;
}
Public static void Play (string filePath)
{_ Player. source = null; try {using (var store = IsolatedStorageFile. getUserStoreForApplication () {using (var stream = new IsolatedStorageFileStream (filePath, FileMode. open, store) {_ player. setSource (stream); _ player. volume = 1.0; _ player. play (); _ player. mediaEnded + = new RoutedEventHandler (sender, e) => {stream. close (); stream. dispose (); _ player. source = null; _ player = null;}); _ player. mediaFailed + = new EventHandler <ExceptionRoutedEventArgs> (s, args) => {stream. close (); stream. dispose (); _ player. source = null; _ player = null;}) ;}} catch (Exception) {_ player. source = null; _ player = null ;}}