Can't get Tone.js player to work and play a single wav file
P粉231079976
2023-09-01 10:34:17
<p>无法让 Tone Player 播放任何内容,这是我的简单 VueJs 代码:</p>
<pre class="brush:php;toolbar:false;"><template>
<div>
<h1>Simple Tone.js Demo</h1>
<button style="background-color: cadetblue; padding: 4px 10px;" @click="play">Play</button>
</div>
</template>
<script>
import * as Tone from "tone";
export default {
data() {
return {
player: null,
};
},
methods: {
async play() {
try {
console.log("Tone.js context state:", Tone.context.state);
if (Tone.context.state !== "running") {
await Tone.start();
console.log("audio context started");
}
this.player.start();
} catch (error) {
console.error("Error during playback:", error.message, error);
}
},
async initializePlayer() {
console.log(Tone.context.state);
try {
this.player = await new Tone.Player({
url: "/sounds/rain.wav",
loop: true,
autostart: false,
}).toDestination();
this.player.loaded;
} catch (error) {
console.error("Error loading audio file:", error);
}
console.log("Audio file loaded", this.player.loaded);
},
},
created() {
this.initializePlayer();
},
};
</script></pre>
<p>我正在加载的声音存在于正确的位置 sound/rain.wav 并且如果我在 chrome 中输入它的路径,浏览器能够正确打开它
http://localhost:5173/sounds/rain.wav
</p>
<p>运行应用程序得到的输出:</p>
<p>了解 Tone.js 的人可以帮助我让播放器播放单个文件吗?我花了一整天的时间来解决这个问题,甚至使用了 GPT4,但我遇到了同样的问题,播放器无法播放简单的文件。</p>
I guess the error occurred because
Player
has not finished downloading the audio.The constructor does not return a promise. If you want to wait until the
Player
is ready, you need to pass theonload
function. By wrapping it in a Promise, it can be used to wait for thePlayer
to be ready.