alemangui / pizzicato

Library to simplify the way you create and manipulate sounds with the Web Audio API.
https://alemangui.github.io/pizzicato/
MIT License
1.67k stars 132 forks source link

How to change the playback rate while preserving the pitch #169

Closed rtwalz closed 2 years ago

rtwalz commented 2 years ago

I spent a few hours trying to figure out how to change the playback rate while preserving the pitch, and apply a filter from Pizzicato. The catch is that you have to create the AudioNode elsewhere, like in an <audio> tag in the DOM, not using Pizzicato.Sound constructor (maybe it's possible with the constructor but I couldn't figure it out).

I assume other people want to know how to do this, here is what worked for me:

js:

function main(){
    let audio = document.querySelector("audio")
    Pizzicato.context = new AudioContext()
    audio.playbackRate = 2
    audio.preservesPitch = true

    let audioNode = Pizzicato.context.createMediaElementSource(audio)
    let analyser = Pizzicato.context.createAnalyser();

    let lowPassFilter = new Pizzicato.Effects.LowPassFilter({
        frequency: 1500,
        peak: 10
    });

    node.connect(lowPassFilter)
    lowPassFilter.connect(analyser).connect(Pizzicato.context.destination);
}

html:

<button onclick="main()"> Play </button>
<audio controls>
  <source src="/songs/00d0ef226e2f867ddf7761e81d921cac85eb46df.mp3" type="audio/mpeg">
</audio>