问题
I'm developing a UWP that contains a WebApp that has some JS functions that invokes some C# functions. Nowadays, I'm trying to play a sound that I have stored in the Assets folder of my UWP app:
This is the function that I'm trying to play of my Windows Runtime Component:
public async void Beep()
{
await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async () =>
{
MediaElement mysong = new MediaElement();
StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
StorageFolder soundsFolder = await folder.GetFolderAsync("sounds");
StorageFile file = await soundsFolder.GetFileAsync("beep.mp3");
var stream = await file.OpenAsync(FileAccessMode.Read);
mysong.SetSource(stream, file.ContentType);
mysong.Play();
});
}
By the way, I also tried this code and it didn't work too:
public async void Beep()
{
MediaElement mysong = new MediaElement();
StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
StorageFolder soundsFolder = await folder.GetFolderAsync("sounds");
StorageFile file = await soundsFolder.GetFileAsync("beep.mp3");
var stream = await file.OpenAsync(FileAccessMode.Read);
mysong.SetSource(stream, file.ContentType);
mysong.Play();
}
This is structure of the location of the file:
And this is how I'm calling it from JS:
CallJSCSharp.Beep();
I have more functions inside the Windows Runtime Component and all of them are working as expected with exception of this one. Thanks for your help.
回答1:
I found the how to fix it:
I added both projects in the same solution:
- UWP project.
- Windows Runtime Component.
I removed extra code from the function (it's unnecessary to add the Media Element in the XAML as suggested before).
public async void Beep() { MediaElement mysong = new MediaElement(); StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets"); StorageFolder soundsFolder = await folder.GetFolderAsync("sounds"); StorageFile file = await soundsFolder.GetFileAsync("beep.mp3"); var stream = await file.OpenAsync(FileAccessMode.Read); mysong.SetSource(stream, file.ContentType); mysong.Play(); }
Important to remember when you call any JS function, it must be with lower cases because JS conventions (even if your function has been written with upper cases).
CallJSCSharp.beep();
More information about JS Conventions:
Using the Windows Runtime in JavaScript
回答2:
MediaElement
needs to be added to a XAML UI tree to work; you should just use the MediaPlayer API instead. You don't even need to write C# code to do it - you should be able to access the API directly from JavaScript (if you want to). More on the Media Playback overview page
来源:https://stackoverflow.com/questions/49199184/how-to-play-a-sound-from-js-in-a-uwp-app