我尝试在游戏中添加音频,但是当我使用 this.sound.add('') 调用该音频时,遇到错误“缓存中丢失”
//预加载场景
preload () {
this.load.audio('stretchAudio', './assets/t1.mp3');
}
//游戏场景
create{
this.sound.add('stretchAudio');
}
//webpack 基础
const Dotenv = require('dotenv-webpack');
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
mode: "development",
devtool: "eval-source-map",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: [/\.vert$/, /\.frag$/],
use: "raw-loader"
},
{
test: /\.(gif|png|jpe?g|svg|xml)$/i,
use: "file-loader"
},
{
test: /\.(mp3|wav|ogg)$/i,
use: "file-loader"
}
]
},
plugins: [
// _ADD
new Dotenv(),
new CleanWebpackPlugin({
root: path.resolve(__dirname, "../")
}),
new webpack.DefinePlugin({
CANVAS_RENDERER: JSON.stringify(true),
WEBGL_RENDERER: JSON.stringify(true)
}),
new HtmlWebpackPlugin({
template: "./index.html"
})
]
};
//webpack 产品
// _ADD
const Dotenv = require('dotenv-webpack');
const { merge } = require("webpack-merge");
const path = require("path");
const base = require("./base");
const TerserPlugin = require("terser-webpack-plugin");
module.exports = merge(base, {
mode: "production",
output: {
filename: "bundle.min.js"
},
devtool: false,
performance: {
maxEntrypointSize: 900000,
maxAssetSize: 900000
},
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
output: {
comments: false
}
}
})
]
},
// _ADD
plugins: [new Dotenv()]
});
//索引js
import Phaser from 'phaser';
import PlayScene from './PlayScene';
import QuestionScene from './QuestionScene';
import PreloadScene from './PreloadScene';
const Scenes = [PlayScene, QuestionScene];
const createScene = Scene => new Scene()
const initScenes = () => Scenes.map(createScene)
const config = {
type: Phaser.CANVAS,
width: window.screen.width,
height: window.screen.height,
scale: {
mode: Phaser.Scale.FIT,
parent: 'game-container',
width: window.screen.width,
height: window.screen.height
},
physics: {
default: 'arcade',
// arcade: {
// debug: true
// }
},
audio: {
disableWebAudio: false // You can set this to true to disable Web Audio API explicitly
},
scene: [PreloadScene, PlayScene, QuestionScene]
};
new Phaser.Game(config);
问题的要点是,您需要加载/导入文件,以便 webpack 知道它存在并可以使用它。 请参阅下面的代码片段了解详细信息。
导入
import some_name_you_want_to_use from "./assets/test.mp3";
不,您可以在代码中使用导入的文件。
使用文件
...
preload (){
this.load.audio('stretchAudio', some_name_you_want_to_use);
}
...
这应该可以解决你的问题。