How does ShaderToy load sounds into a texture

折月煮酒 提交于 2019-12-04 11:32:50

You can get audio data from the Web Audio API be creating an analyser node

const audioContext = new window.AudioContext();
const analyser = audioContext.createAnalyser();

Then create a buffer to receive teh data

const numSamples = analyser.frequencyBinCount;
const audioData = new Uint8Array(numSamples);

Then in your render loop get the data and put it in a texture

analyser.getByteFrequencyData(audioData);
...
gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, numSamples, 1, 0,
              gl.LUMINANCE, gl.UNSIGNED_BYTE, audioData);

or in three.js use a DataTexture

That's the short version. The longer version is audio needs to be on the same domain or you'll run into CORS issues. To get data for an audio stream like an <audio> tag's you'd call

const source = audioContext.createMediaElementSource(audio);

That doesn't work in mobile Chrome nor mobile Safari at the moment and there are bugs in Safari.

Here's a working sample

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