xxxxxxxxxx
51
// this code works in safari, unlike the p5.audioIn getLevel method.
let analyserNode;
async function getMedia(constraints) {
try {
let stream = null;
stream = await navigator.mediaDevices.getUserMedia(constraints);
/* use the stream */
const audioContext = new AudioContext();
const mediaStreamAudioSourceNode = audioContext.createMediaStreamSource(
stream
);
analyserNode = audioContext.createAnalyser();
mediaStreamAudioSourceNode.connect(analyserNode);
return analyserNode
} catch (err) {
/* handle the error */
}
}
function getVolume() {
if (!analyserNode) {
return 0;
}
const pcmData = new Float32Array(analyserNode.fftSize);
analyserNode.getFloatTimeDomainData(pcmData);
let sumSquares = 0.0;
for (const amplitude of pcmData) {
sumSquares += amplitude * amplitude;
}
return Math.sqrt(sumSquares / pcmData.length);
}
function setup() {
getMedia({
audio: true,
video: false,
});
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(0);
let vol = getVolume();
let rh = map(vol, 0, 0.5, 0, height);
console.log(vol)
rect(0, height, width, -rh);
}