我正在使用 NativeScript 与 Angular 2 和最新的 Webpack 工作流程,并且我正在使用 iOS 模拟器。我正在使用 nativescript-audio 插件在点击按钮时播放声音文件。
我的目标是播放应用程序内置的本地声音文件,而不使用任何互联网连接来流式传输或先下载它们。
我已经下载并尝试了我能找到的每个演示应用程序,并完全按照我自己的应用程序中的说明进行操作,但是当我在其他地方引用网络服务器上的声音文件时,我只能让插件播放声音。尝试播放本地存储的 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“(null)”
系统出现错误: 控制台错误 file:///app/vendor.js:41405:24:错误错误:未捕获(承诺中):TypeError:null 不是对象(正在评估“_this._player.play”)
据我了解,错误告诉我它找不到该文件,这似乎是有道理的,因为当我打开编译的应用程序文件时,我在任何地方都找不到声音文件。
确保您的音频文件在构建过程中捆绑,默认构建配置不包含 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)}/**`] },
),
使用
{ from: { glob: "audio/**" } },
更新 CopyWebpackPlugin 配置也会在构建过程中捆绑您的音频文件夹。
尝试了这个选项 webpack.Utils.addCopyRule('app/assets/**/*'); 我仍然收到错误:java.io.FileNotFoundException:/data/data/org.nativescript.yogaflow/files/app/assets/audio/sino.mp3:打开失败:ENOENT(没有这样的文件或目录)