I tried adding audio in my game but when I call that audio using this.sound.add(”) it encountered an error ‘missing from cache’
//preload scene
preload () {
this.load.audio('stretchAudio', './assets/t1.mp3');
}
//playscene
create{
this.sound.add('stretchAudio');
}
//webpack base
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 prod
// _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()]
});
//index 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);
2
The gist of the problem is, that you need to load/import the file, so that webpack knows it exists and can work with it. See the code snippets below for details.
Importing audio file
import some_name_you_want_to_use from "./assets/test.mp3";
And no you can to use the imported file in the code.
Using the imported file
(the names have too match)
...
preload (){
this.load.audio('stretchAudio', some_name_you_want_to_use);
}
...
this should solve your problem.