I finally found something that helps accomplish what I want. I have taken what Diederik Krols has posted a year ago and adapted for my use. He describes using a singleton class but I find I don't need singleton for my purpose. I created a custom class to load up the sounds and then I declare static variable in App.xaml.cs and instantiate it there. This makes the sounds globally available by referencing App.MyAppSounds. I'm willing to share, here is my soundeffects class and how I use it adapted from this article
public enum SoundEfxEnum { NORMALMOVE, CHECK, CAPTURE, CASTLING, } public class SoundEffects { private Dictionaryeffects; public SoundEffects() { effects = new Dictionary (); LoadEfx(); } private async void LoadEfx() { effects.Add(SoundEfxEnum.NORMALMOVE, await LoadSoundFile("normalmove.wav")); effects.Add(SoundEfxEnum.CHECK, await LoadSoundFile("check.wav")); effects.Add(SoundEfxEnum.CAPTURE, await LoadSoundFile("capture.wav")); effects.Add(SoundEfxEnum.CASTLING, await LoadSoundFile("castling.wav")); } private async Task LoadSoundFile(string v) { MediaElement snd = new MediaElement(); snd.AutoPlay = false; StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("sounds"); StorageFile file = await folder.GetFileAsync(v); var stream = await file.OpenAsync(FileAccessMode.Read); snd.SetSource(stream, file.ContentType); return snd; } public async Task Play(SoundEfxEnum efx) { var mediaElement = effects[efx]; await mediaElement.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { mediaElement.Stop(); mediaElement.Play(); }); } }
In App.xaml.cs I declare the variable:
sealed partial class App : Application { public static SoundEffects MyAppSounds; ////// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// public App() { this.InitializeComponent(); this.Suspending += OnSuspending; }
In OnLaunched in App.xaml.cs at end just before Window is activated, I instantiate the static variable
// My Application Sound Effects MyAppSounds = new SoundEffects(); // Ensure the current window is active Window.Current.Activate(); }
To use it, I do this anytime I want to play the sound
// Play a sound effect App.MyAppSounds.Play(SoundEfxEnum.Check); // Or asynchronously await App.MyAppSounds.Play(SoundEfxEnum.Check);
文字地址: https://social.msdn.microsoft.com/Forums/windowsapps/en-US/ddb1b7f1-e988-40c7-8e1e-eaf6d8573ec2/uwp-how-to-play-sound-from-wav-fileresource?forum=wpdevelop