首页 > 解决方案 > 音频播放器插件播放 URL 声音,但不播放本地声音文件

问题描述

我正在将 NativeScript 与 Angular 2 和最新的 Webpack 工作流程一起使用,并且我正在使用 iOS 模拟器。当我点击一个按钮时,我正在使用 nativescript-audio 插件来播放声音文件。

我的目标是播放应用程序内置的本地声音文件,而无需使用任何互联网连接来流式传输或先下载它们。

我已经下载并尝试了我能找到的每个演示应用程序,并在我自己的应用程序中完全按照说明进行操作,但是当我在其他地方引用 Web 服务器上的声音文件时,我只能让插件播放声音。尝试播放本地存储的 mp3 文件不起作用。

我还使用了 tns-core-modules/file-system 模块来搜索我引用的文件,但是我在编译的应用程序中的任何地方都找不到该文件。似乎该文件甚至根本没有包含在构建过​​程中,我不知道为什么。

我发现的所有示例应用程序都只能播放存储在外部服务器上的文件。他们也都在使用过时的 Legacy 工作流程,而且没有一个人使用 Angular 2 系统。

这是我的 component.html 文件:

<ActionBar class="action-bar">
  <Label class="action-bar-title" text="Sound Page"></Label>
</ActionBar>

<StackLayout orientation="vertical" width="100%" height="100%">
  <Button class="btn btn-primary btn-rounded-sm" id="playButton" text="Play Sound"
    (tap)="onPlayTap($event)"></Button>
</StackLayout>

这是我的 Angular 2 component.ts 文件:

import { Component } from "@angular/core"
import { TNSPlayer } from "nativescript-audio"

const player = new TNSPlayer()
const playerOptions =
{
  audioFile: "~/audio/session_1.mp3",
  loop: false,
  autoplay: false
}

@Component({
  selector: "SongPage",
  moduleId: module.id,
  templateUrl: "./song-page.component.html"
})
export class SongPageComponent {

  constructor()
  {
    player
      .initFromFile(playerOptions)
      .then(res => console.log(res))
      .catch(err => console.log("something went wrong...", err))
  }

  onPlayTap() { player.play() }
}

我从 player.initFromFile 承诺中得到一个错误,而不是播放声音文件:

控制台日志文件:///app/vendor.js:59907:39:出了点问题...错误域=NSOSStatusErrorDomain 代码=2003334207“(空)”

并且来自系统的错误:CONSOLE ERROR file:///app/vendor.js:41405:24: ERROR Error: Uncaught (in promise): TypeError: null is not an object (evalating '_this._player.play')

据我了解,错误告诉我它找不到文件,这似乎是有道理的,因为当我打开编译的应用程序文件时,我在任何地方都找不到声音文件。

  1. 我的代码本身有问题吗?
  2. 如果没有,我如何确保该文件包含在应用程序的编译文件中并确保插件可以找到它?

标签: nativescriptnativescript-angularnativescript-plugin

解决方案


确保您的音频文件在构建期间捆绑,默认构建配置不包括 mp3 文件,而仅包括图像文件、字体和资产。

webpack.config.js

        // Copy assets to out dir. Add your own globs as needed.
        new CopyWebpackPlugin(
            [
                { from: { glob: "assets/**" } },
                { from: { glob: "fonts/**" } },
                { from: { glob: "**/*.jpg" } },
                { from: { glob: "**/*.png" } },
                { from: { glob: "audio/**" } },
            ],
            { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] },
        ),

在构建过程中更新 CopyWebpackPlugin 配置{ from: { glob: "audio/**" } },也会捆绑您的音频文件夹。


推荐阅读