How to change the pitch with JavaScript?

孤街浪徒 提交于 2021-02-07 09:56:09

问题


Let’s say you have an audio variable called audio and it stores a sound.

I know how to change the speed for example:

audio.playBackRate = 2; 

But I don't know how to change the pitch.

Is there an audio.pitch attribute or do I have to create it myself?

I want to do something like this:

var audio = new Audio();
audio.src = "sound_effect.wav";
audio.pitch = 2 //doubling the pitch but there is no pitch attribute
audio.play();

回答1:


I think you need to use a library to apply pitch shifting to your audio signal. You could use the Tone.js PitchShift. See this JSFiddle of GitHub user Jexim for a working example. I copy-pasted the most importand parts from this fiddle below:

Javascript:

var player = new Tone.Player("http://example.com/my-audiofile.mp3").sync().start(0);

var pitchShift = new Tone.PitchShift({
    pitch: -5
}).toMaster();

player.connect(pitchShift);

Tone.Buffer.on('load', () => {
    alert('Ready for play');
});

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

HTML:

<script src="https://unpkg.com/tone@next/build/Tone.js"></script>
<button onclick="play()">Play</button>


来源:https://stackoverflow.com/questions/53876757/how-to-change-the-pitch-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!