如何将 Web Audio API 连接到 Tone.js?

Aad*_*elu 2 javascript audio node.js web-audio-api tone.js

我正在做一个在线音频播放器,所以我想在我的应用程序中集成Pitch Shifter,它在Tone js上可用,但在Web Audio API 中不可用......

所以我的想法是将Tonejs Pitch Shifter连接到Web Audio API 的 audioContext

有什么可能的方法吗?

这是我的代码供参考

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

Run Code Online (Sandbox Code Playgroud)

chr*_*din 6

我猜你想实现这样的信号流:

mediaElement > gainNode > pitchShift > destination
Run Code Online (Sandbox Code Playgroud)

为了确保 Tone.js 使用相同的 AudioContext,您可以使用 Tone 对象上的 setter 来分配它。这需要在使用 Tone.js 执行任何其他操作之前完成。

Tone.context = context;
Run Code Online (Sandbox Code Playgroud)

Tone.js 还导出了一个助手,可用于将本机 AudioNode 连接到 Tone.js 提供的节点。

Tone.connect(gainNode, pitchShift);
Run Code Online (Sandbox Code Playgroud)

我稍微修改了您的示例代码以合并更改。

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);
Run Code Online (Sandbox Code Playgroud)