sora sora - 2 months ago 52
TypeScript Question

Playing audio with Phaser

Could anyone help me with the Phaser sound issue?

I have coded a button with a function that plays sound in TypeScript, but when I press the button on chrome, Phaser gives me the following warning on the chrome console:

Phaser.Cache.getSound: Key "sample" not found in Cache.


At first, I thought that the mp3 file has not been fully loaded when I pressed the button, but even when I wait enough amount of time, the situation is still the same...

export class PlayState extends Phaser.State {

private sampleSound: Phaser.Sound;
private testButton: Phaser.Sprite;

preload() {
this.load.image("test", "assets/image/test.png")
this.load.audio("sample", "assets/audio/sample.mp3");
}

create() {
// Add test button
this.testButton = this.add.sprite(50, 50, "test");
this.testButton.anchor.setTo(0.5);
this.testButton.inputEnabled = true;
this.testButton.events.onInputDown.add(this.test);

// Add audio
this.sampleSound = this.add.audio("sample");
}

private test = () => {
this.sampleSound.play();
}
}


I certainly have the sample.mp3 file under assets/audio directory, so Phaser should be able to find it.

Answer

Place the mp3 file under the folder of the transpiled javascript file. In my case, the TypeScript was looking for source/assets/audio/sample.mp3, but the transpiled javascript was looking for dist/assets/audio/sample.mp3.
(test.png was already there, so Phaser was able to find it. But I totally forgot to place the mp3 file...)

When you are using TypeScript, be always aware that scripts are executed after they are transpiled.