Skip to content

Commit

Permalink
Docs: phase vocoder example (#3791)
Browse files Browse the repository at this point in the history
* Docs: phase vocoder example

* Simplify code
  • Loading branch information
katspaugh authored Jul 21, 2024
1 parent 4d5b56f commit 145c604
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
64 changes: 64 additions & 0 deletions examples/phase-vocoder/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// WebAudio speed control with pitch preservation

import WaveSurfer from 'wavesurfer.js'

// Init wavesurfer
const wavesurfer = WaveSurfer.create({
backend: 'WebAudio',
container: document.body,
waveColor: 'violet',
progressColor: 'purple',
url: '/examples/audio/librivox.mp3',
})

// Wait for the audio to be ready
wavesurfer.on('ready', async () => {
const webAudioPlayer = wavesurfer.getMediaElement()
const gainNode = webAudioPlayer.getGainNode()
const audioContext = gainNode.context

// Load the phase vocoder audio worklet
await audioContext.audioWorklet.addModule('/examples/phase-vocoder/phase-vocoder.min.js')
const phaseVocoderNode = new AudioWorkletNode(audioContext, 'phase-vocoder-processor')

// Connect the worklet to the wavesurfer audio
gainNode.disconnect()
gainNode.connect(phaseVocoderNode)
phaseVocoderNode.connect(audioContext.destination)

// Speed slider
document.querySelector('input[type="range"]').addEventListener('input', (e) => {
const speed = e.target.valueAsNumber
document.querySelector('#rate').textContent = speed.toFixed(2)
wavesurfer.setPlaybackRate(speed)
const pitchFactorParam = phaseVocoderNode.parameters.get('pitchFactor')
pitchFactorParam.value = 1 / speed
})

// Play/pause button
document.querySelector('button').addEventListener('click', () => {
wavesurfer.playPause()
})
})

/*
<html>
<div style="display: flex; margin: 1rem 0; gap: 1rem;">
<button>
Play/pause
</button>
<label>
Playback rate: <span id="rate">1.00</span>x
</label>
<label>
0.1x <input type="range" min="0.1" max="4" step="0.1" value="1" /> 4x
</label>
</div>
<p>
📖 Based on <a href="https://github.com/olvb/phaze" target="_top">github.com/olvb/phaze</a>
</p>
</html>
*/
1 change: 1 addition & 0 deletions examples/phase-vocoder/phase-vocoder.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 145c604

Please sign in to comment.