【问题标题】:How to play a sound from JS in a UWP app?如何在 UWP 应用中播放来自 JS 的声音?
【发布时间】:2018-08-18 08:17:26
【问题描述】:

我正在开发一个 UWP,其中包含一个 WebApp,该 WebApp 具有一些调用一些 C# 函数的 JS 函数。现在,我正在尝试播放存储在 UWP 应用的 Assets 文件夹中的声音:

这是我尝试使用的 Windows 运行时组件的功能:

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();
    });
}

顺便说一句,我也试过这个代码,它也不起作用:

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();
}

这是文件所在位置的结构:

这就是我从 JS 中调用它的方式:

CallJSCSharp.Beep();

我在 Windows 运行时组件中有更多功能,除此之外,所有功能都按预期工作。感谢您的帮助。

【问题讨论】:

标签: javascript audio webview uwp windows-10-universal


【解决方案1】:

MediaElement 需要添加到 XAML UI 树中才能工作;你应该改用MediaPlayer API。您甚至不需要编写 C# 代码来执行此操作 - 您应该能够直接从 JavaScript 访问 API(如果您愿意的话)。更多关于Media Playback overview page

【讨论】:

  • 嗨彼得,据我所知,任何调用 C# 函数的 JS 都必须在 Windows 运行时控件中编写,我知道因为它不是我调用的第一个函数,所以我有函数保持屏幕打开,从 JSON 生成 Excel 或在外部浏览器中打开 URL。这就是为什么我确定我的特定功能有问题。现在,假设您的场景,我将控件添加到 XAML,我如何从 WRC 中选择它?因为由于 UWP 限制,我无法在主项目中声明类或其他任何内容。感谢您的澄清。
【解决方案2】:

我找到了解决方法:

  1. 我在同一个解决方案中添加了两个项目:

    • UWP 项目。
    • Windows 运行时组件。

  1. 我从函数中删除了额外的代码(没有必要按照之前的建议在 XAML 中添加媒体元素)。

    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();
    }
    
  2. 重要的是要记住,当您调用任何 JS 函数时,它必须使用 小写,因为 JS 约定(即使您的函数是用大写编写的)。

    CallJSCSharp.beep();
    

更多关于 JS 约定的信息:

Using the Windows Runtime in JavaScript

【讨论】:

    猜你喜欢
    • 2016-03-06
    • 2016-10-31
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    相关资源
    最近更新 更多