首页 > 解决方案 > 如何使用 JavaScript / Tone.js 更改音高和播放速率?

问题描述

我想同时完成两件事:

1) 将声音文件的播放速率更改为 1/2 速度

2) 将音调降低五分之一

最后,我不想使用单独的按钮来播放结果,而是将其连接到音频标签并在那里使用播放按钮。

下面是迄今为止我使用 Tone.js 得到的最接近的结果。我真的在为文档苦苦挣扎,但我知道 Tone.Transport.bpm.value = 60; 将 bpm 从 120 更改为 60,Tone.PitchShift 将歌曲移调。我只是不知道如何将两者结合起来“叠加”效果。

以下是我关注的一些链接:

如何用 JavaScript 改变音高?

https://tonejs.github.io/docs/r12/PitchShift

https://tonejs.github.io/docs/13.8.25/Transport

在此先感谢您的帮助!

<audio id="myAudio" controls preload="none">
      <source src="my_tune.m4a" type="audio/mp4" >
</audio>

<script src="https://unpkg.com/tone@next/build/Tone.js"></script>

<script>

Tone.Transport.bpm.value = 60;  // setting the bpm like this is not working. where to put this?


var player = new Tone.Player("my_tune.m4a").sync().start(0);
// is it possible to use audio tag instead of creating this player?

var pitchShift = new Tone.PitchShift({
    pitch: -5 // this is working and lowers pitch by a fifth
}).toMaster();

player.connect(pitchShift);
window.play = function() {
    Tone.Transport.start();
}

<script>

<button onclick="setPlaySpeed()" type="button">separate button</button><br>

标签: javascriptperformanceaudiopitch

解决方案


更新:工作解决方案

我找到了一种可行的方法:首先设置播放速率。然后,在设置音高时,您需要计算要添加/减去多少音高偏移以补偿播放速率。在我的示例中,我必须为 0.5 的播放速率补偿 +12 音高偏移。

player = new Tone.Player("url/to/audio.mp3");
playback_rate = 0.5 // or 1 (I only implemented these two options)
transpose_by = 7 // up 7 half steps, -7 would be down 7 half steps

// set playback rate
player.playbackRate = playback_rate
player.toDestination();


// set pitch shift
if (playback_rate == 1){
    pitch_shift = new Tone.PitchShift({
    pitch: transpose_by.toString()
    }).toDestination();
} else { //if playbackrate == 0.5 add +12 to pitch to correct
    trans = transpose_by + 12
    trans = trans.toString()
    pitch_shift = new Tone.PitchShift({
    pitch: trans
  }).toDestination();
}
player.disconnect(); // disconnect old player (get overlay of two players otherwise if you repeat this)
player.connect(pitch_shift);

player.start()

在我的网站上查看它的实际效果:https ://www.lickstack.com

不过,我仍然不知道如何将 Tone.js 播放器连接到音频元素。任何帮助,将不胜感激。在这里查看我的帖子: create html <audio> element from Tone.js object


推荐阅读