Can't get Tone.js player to work and play a single wav file
P粉231079976
P粉231079976 2023-09-01 10:34:17
0
1
628
<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>
P粉231079976
P粉231079976

reply all(1)
P粉331849987

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 the onload function. By wrapping it in a Promise, it can be used to wait for the Player to be ready.

this.player = await new Promise((resolve, reject) => {
    const player = new Tone.Player({
        loop: true,
        onerror: (err) => reject(err),
        onload: () => resolve(player),
        url: '/sounds/rain.wav'
    });
});

this.player.toDestination();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template