Connect microphone to Analyser to get hertz with javascript

Asked

Viewed 80 times

0

How do I connect the audio input from the microphone to the Audiocontext API’s Analyser to get the frequency in Hertz?

Javascript:

let display = document.getElementById("display");
let ctx = new AudioContext();
var analyser = ctx.createAnalyser();
analyser.connect(ctx.destination);

navigator.mediaDevices
    /* Solicita permissão de acesso */
    .getUserMedia({ audio: { echoCancellation: true } })
    /* Cria um fonte de stream */
    .then(stream => {
        let source = ctx.createMediaStreamSource(stream);
        source.connect(analyser);
        display.innerText = analyser.getFloatFrequencyData()[0];
    })
    .catch(err => {
        console.log("Microfone negado");
    });

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API JS</title>
</head>
<body>
    <!-- <audio id="playerAudio" src="" autoplay controls></audio> -->
    <p id="display">0</p>
    <script src="/script.js"></script>
</body>
</html>

I’m not able to do this work, if I connect the variable stream of then() directly to an audio object (with bausa and mute control...) I can hear at the same time I record, but I cannot intercept with the Analyser to get the Hertz audio.

1 answer

0

Can connect an Analyser and a Scriptprocessor.

var display = document.getElementById("display");

navigator.mediaDevices.getUserMedia({audio: true})
.then(function(stream) {
    var ctx = new AudioContext();
    /* Cria um fonte de stream */
    var source = ctx.createMediaStreamSource(stream);
    var analyser = ctx.createAnalyser();
    var processor = ctx.createScriptProcessor(256, 1, 1);
    source.connect(processor);
    source.connect(analyser);
    processor.connect(ctx.destination);

    processor.onaudioprocess = (data) => {
        var dataArray = new Float32Array(analyser.frequencyBinCount);

        setInterval(() => {
            analyser.getFloatFrequencyData(dataArray);
            display.innerHTML = dataArray;
        }, 1000);
    }


})
.catch(err => {
  console.log(err.message);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.