我是tone.js的新手,我只想要一个简单的暂停按钮。我知道有stop()和start(),但这不是暂停,当再次开始时,音乐只会转到歌曲的开头。
我使用tone.js,因为我想操纵音乐,做一些合成声音。我也使用p5.js,但不知何故暂停不起作用。它抛出一个错误:“无法读取未定义的属性'length‘。所以我想使用tone.js,但只需要弄清楚如何暂停音乐。谢谢。”
下面是代码
var player = new Tone.Player("data/audio/singingbird_audio.mp3").toMaster();
var whale = new Tone.Player("data/audio/whale.mp3").toMaster();
whale.autostart = false;
whale.volume.value = -10;
player.autostart = false;
player.volume.value = 5;
player.stop();
button = createButton('Play Bird');
button.position(20, 200);
button.mousePressed(birdSwitch);
function birdSwitch() {
if (player.state == "started") {
player.stop();
whale.stop();
} else if (player.state == "stopped") {
player.start();
whale.start();
}
}
发布于 2020-11-18 13:12:23
不知道为什么约翰尼斯会这么扫兴。绝对没有理由不使用Tone.js。这是一个非常酷的库。
此外,实际的解决方案比约翰斯提出的解决方案更容易。
解决方案
从字面上看,您需要做的就是将播放器对象同步到Tone.Transport,然后您可以通过控制传输而不是播放器来玩/暂停/停止一整天
var player = new Tone.Player("data/audio/singingbird_audio.mp3").toMaster();
var whale = new Tone.Player("data/audio/whale.mp3").toMaster();
// sync the Players to the Transport like this
player.sync().start(0);
whale.sync().start(0);
whale.volume.value = -10;
player.volume.value = 5;
button = createButton('Play Bird');
button.position(20, 200);
button.mousePressed(birdSwitch);
function birdSwitch() {
if (player.state == "started") {
// Use the Tone.Transport to pause audio
Tone.Transport.pause();
} else if (player.state == "stopped") {
// Use the Tone.Transport to start again
Tone.Transport.start();
}
}
如果你想让程序的用户界面更简单,你也可以考虑使用"tonejs-ui.js“库,它有一个很棒的播放/暂停/停止按钮。
只需在<head>
中包含指向"tonejs-ui.js“库的链接,然后就可以在HTML中使用<tone-play-toggle>
元素,并为其添加一个触发传输开始/暂停的事件侦听器。
下面是您需要添加到HTML文件中的代码示例,以及添加到javascript中的事件侦听器,而不是用于您自己的按钮的逻辑。希望这是有意义的。
<head>
<!-- The tonejs-ui.js CDN link -->
<script type="text/javascript" src="https://unpkg.com/@tonejs/ui@0.0.8/build/tonejs-ui.js"></script>
</head>
<body>
<tone-content>
<tone-play-toggle></tone-play-toggle>
</tone-content>
<script type="text/javascript">
document.querySelector("tone-play-toggle").addEventListener("play", (e) => {
const playing = e.detail;
if (playing){
Tone.Transport.start();
} else {
Tone.Transport.pause();
}
});
</script>
</body>
发布于 2020-09-29 16:44:07
对于只播放mp3文件来说,Tone.js有点过头了。
为什么不直接使用<audio>
-Tag呢?这样你就可以直接播放和暂停它。
<button id="pause">Play/Pause</button>
<audio
id="audioNode"
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-7.mp3"
controls
></audio>
const audio = document.getElementById("audioNode");
document.getElementById("pause").addEventListener("click", () => {
if (audio.paused) {
audio.play();
} else {
audio.pause();
}
});
Codesandbox:https://codesandbox.io/s/charming-wiles-ehy8y
在Tonejs中,播放器只是音频缓冲区的包装器。播放、暂停等是通过将播放器同步到Transport类并使用传输播放、暂停、停止功能来完成的。然后传播给玩家。但是因为Transport有一个内部时间表,所以我不认为这是您需要的,因为您必须将Transport重置到正确的位置,等等。
我想最终对你来说,退回到更简单的解决方案会更方便。
https://stackoverflow.com/questions/64090459
复制相似问题