Aadarsh velu
Aadarsh velu

Reputation: 160

How to connect Web Audio API to Tone.js?

I'm doing an Online Audio Player, so I want to integrate Pitch Shifter in my App, which is available on Tone js but not in Web Audio API...

So my idea is to connect Tonejs Pitch Shifter to Web Audio API's audioContext.

Is there any possible ways?

Here is my code for a reference

var audioCtx = new (window.AudioContext || window.webkitAudioContext);

var mediaElem = document.querySelector('audio');

var stream = audioCtx.createMediaElementSource(mediaElem);

var gainNode = audioCtx.createGain();

stream.connect(gainNode);

// tone js

var context = new Tone.Context(audioCtx); // Which is Mentioned in Tonejs Docs!

var pitchShift = new Tone.PitchShift().toMaster();

pitchShift.connect(gainNode);

// Gives Error!
gainNode.connect(audioCtx.destination);

Upvotes: 4

Views: 3095

Answers (1)

chrisguttandin
chrisguttandin

Reputation: 9066

I guess you want to achieve a signal flow like this:

mediaElement > gainNode > pitchShift > destination

To make sure Tone.js is using the same AudioContext you can assign it by using the setter on the Tone object. This needs to be done before doing anything else with Tone.js.

Tone.context = context;

Tone.js also exports a helper which can be used to connect native AudioNodes to the nodes provided by Tone.js.

Tone.connect(gainNode, pitchShift);

I modified your example code a bit to incorporate the changes.

var audioCtx = new (window.AudioContext || window.webkitAudioContext);
var mediaElem = document.querySelector('audio');
var stream = audioCtx.createMediaElementSource(mediaElem);
var gainNode = audioCtx.createGain();

// This a normal connection between to native AudioNodes.
stream.connect(gainNode);

// Set the context used by Tone.js
Tone.context = audioCtx;

var pitchShift = new Tone.PitchShift();

// Use the Tone.connect() helper to connect native AudioNodes with the nodes provided by Tone.js
Tone.connect(gainNode, pitchShift);
Tone.connect(pitchShift, audioCtx.destination);

Upvotes: 11

Related Questions