javascript - 一键在tone.js中播放两个音符
问题描述
我正在开发一个网页游戏,点击一个按钮应该连续播放两个音符。我可以使用上传的音频文件和 audio.onended 回调来做到这一点。
function playMusic(){
audio.src = music_array[music_counter++];
audio.play();
audio.onended = function(){
playMusic();
};
}
我可以使用上面的代码块来播放一首歌曲。但是,使用这种方法,我需要事先将所有音频文件上传到 html,我认为这不是一个好方法。因此,我出于同样的目的研究了tone.js,但我无法一个接一个地演奏音符。我试过像这样使用for循环:
music = ["C4;4n", "D4;4n", ...... , "G5;8n"];
for(var i=0; i<range; i++){
parts = music[music_counter++].split(';');
synth.triggerAttackRelease(parts[0], parts[1]);
}
和
for(var i=0; i<range; i++){
playNote();
}
playNote(){
parts = music[music_counter++].split(';');
synth.triggerAttackRelease(parts[0], parts[1]);
}
没有运气。我也查看了他们的文档和其他 stackoverflow 帖子。我一直无法弄清楚解决方案。有没有人有任何想法如何实现这一目标?
解决方案
我终于想出了办法。
var synth = new Tone.Synth().toMaster();
var music = [{"time": 0, "note": "A4", "duration": "16n"},
......
{"time": 23.5, "note": "A4", "duration": "8n"},
{"time": 24, "note": "G4", "duration": "4n"}];
function playMusic(){
var part = new Tone.Part(function(time, note){
//the notes given as the second element in the array
//will be passed in as the second argument
console.log(note);
synth.triggerAttackRelease(note.note, note.duration, time);
}, music).start(0);
Tone.Transport.start();
}
推荐阅读
- php - 使用 PHP 获取 AJAX POST
- angular - Angular - 有条件的 div 容器
- php - 如何使用 php 和 mysqli 修复上传图像
- arrays - 如何在显示数组值后创建的数组中选择内存。程序运行时如何用cin选择值
- python - 在python的列表中捕获多组项目
- r - 如何将每个类别的百分比添加到堆积条形图(ggplot2)(对于“非百分比”堆积图)
- mysql - SQL作业#4
- elasticsearch - 在 Elasticsearch 中,为什么我会收到错误消息“默认情况下在文本字段上禁用字段数据”
- mysql - Mysql按周末日期分组
- android - 如何根据片段更改回收视图中项目的外观?