How to connect Web Audio API to Tone.js?

≡放荡痞女 提交于 2019-12-14 03:08:08

问题


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);


回答1:


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);


来源:https://stackoverflow.com/questions/58676929/how-to-connect-web-audio-api-to-tone-js

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