问题描述
我是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();
}
}
解决方法
不知道为什么约翰内斯被这样的嗡嗡声杀死。绝对没有理由不使用Tone.js。这是一个非常酷的库。
此外,ACTUAL解决方案比Johaness解决方案容易,因此无济于事。
解决方案
从字面上看,您需要做的就是将Player对象同步到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();
}
}
其他想法
如果您想使程序的UI更简单,则可能还需要考虑使用“ 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/[email protected]/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>
,
Tone.js只是播放mp3文件有点过分。
为什么不仅仅使用<audio>
标签?
这样,您可以直接播放和暂停它。
<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类并使用Transports播放,暂停,停止功能来完成的。然后传播到玩家。但是由于运输工具有内部时间表,所以我认为这不是您需要的,因为您必须将运输工具重置为正确的位置,等等。
最后,我想让您回到更简单的解决方案会更方便。