leolibra
leolibra

Reputation: 21

Using p5 and ml5 in React

I'm trying to get a pitch detection feature working in my react application using ml5 and p5. I believe the ml5 code that I'm using here connects to the CREPE pitch recognition model. When I try to compile the component that contains my code I am getting this error:

Failed to compile.
src/components/PitchPage.js
  Line 17:11:  'stream' is not defined  no-undef
  Line 18:22:  'stream' is not defined  no-undef
Search for the keywords to learn more about each error.

I'm wondering if anyone can help me figure out what the issue is and how I can get my pitch recognition code working. Could someone post code that would possibly work? I have a feeling that maybe I need to be using classes, components, and render, but I'm not sure. Thank you! Here is my code:

import React from "react";
import * as ml5 from "ml5";
import P5Wrapper from "react-p5-wrapper";

function PitchPage() {
    let audioContext;
        let mic;
        let pitch;

        async function setup() {
          audioContext = new AudioContext();
          stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
          startPitch(stream, audioContext);
          console.log("hi")
        }
        setup();

        function startPitch(stream, audioContext) {
          pitch = ml5.pitchDetection('./model/', audioContext, stream, modelLoaded);
        }

        function modelLoaded() {
          document.querySelector('#status').textContent = 'Model Loaded';
          getPitch();
        }

        function getPitch() {
          pitch.getPitch(function (err, frequency) {
            if (frequency) {
              document.querySelector('#result').textContent = frequency;
              console.log(frequency)
            } else {
              document.querySelector('#result').textContent = 'No pitch detected';
            }
            getPitch();
          })
        }
    // console.log(react-p5)
    // console.log(typeof p5)
    return (
        <div>
    <h1>Pitch Detection Example</h1>
    <p id='status'>Loading Model...</p>
    <p id='result'>No pitch detected</p>
        </div>
    );
  }
  
  export default PitchPage;

Upvotes: 2

Views: 490

Answers (0)

Related Questions