How to change the pitch with JavaScript?
Asked Answered
P

2

7

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();
Pestilential answered 20/12, 2018 at 22:12 Comment(2)
BTW I want to change the pitch without changing the speed.Pestilential
There is this answer that changes the pitch but I’m not sure if it’s what you want. It is SignatureSmileyFaceProductions answer on this link: https://mcmap.net/q/785442/-javascript-pitch-shift-with-time-stretchTyus
A
2

Tone's API appears to have changed somewhat since this answer. Here's code that reflects the latest version (as of 2024):

const url = "https://upload.wikimedia.org/wikipedia/commons/9/90/De-Wolfgang_Amadeus_Mozart.ogg"; // use any valid audio file if this disappears over time...

const btn = document.querySelector("button");
btn.addEventListener("click", async () => {
  await Tone.start();
  const player = new Tone.Player({
    url,
    loop: true,
    autostart: false,
  });
  await Tone.loaded();
  const pitchShift = new Tone
    .PitchShift({pitch: -8})
    .toDestination();
  player.connect(pitchShift);
  player.start();
});
<script src="https://unpkg.com/[email protected]/build/Tone.js"></script>
<button>Play</button>
Amateurism answered 14/1, 2022 at 3:59 Comment(0)
W
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>
Waterproof answered 22/12, 2018 at 8:31 Comment(3)
Thank you for this information. Is there a way to play this without clicking the play button?Pestilential
You can replace the code in Tone.Buffer.on('load', ...) with Tone.Buffer.on('load', () => { Tone.Transport.start(); }); to play it without user interaction.Waterproof
The link to the audio file in JSFiddle link is brokenGriskin

© 2022 - 2024 — McMap. All rights reserved.