YZarytskyi / react-voice-visualizer

React library for audio recording and visualization using the Web Audio API
https://www.npmjs.com/package/react-voice-visualizer
MIT License
95 stars 22 forks source link

Cant change audio input and output source #15

Open Nikkolas-Cage opened 1 month ago

Nikkolas-Cage commented 1 month ago

Cant change audio input and output source here's my current audio stream i want to pass the device id to the visualizer

import React, { useState, useEffect } from "react";
import { Box, Select, Text, VStack } from "@chakra-ui/react";

const AudioInputSelector = () => {
  const [audioInputs, setAudioInputs] = useState([]);
  const [selectedInput, setSelectedInput] = useState("");
  const [currentStream, setCurrentStream] = useState(null);

  useEffect(() => {
    const getAudioDevices = async () => {
      try {
        console.log("Requesting microphone access...");
        await navigator.mediaDevices.getUserMedia({ audio: true });
        console.log("Microphone access granted");

        const devices = await navigator.mediaDevices.enumerateDevices();
        console.log("Devices enumerated:", devices);

        const audioInputDevices = devices.filter(
          (device) => device.kind === "audioinput"
        );
        console.log("Audio Input Devices:", audioInputDevices);

        setAudioInputs(audioInputDevices);

        if (audioInputDevices.length > 0) {
          setSelectedInput(audioInputDevices[0].deviceId);
          setAudioInput(audioInputDevices[0].deviceId);
        }
      } catch (error) {
        console.error("Error fetching audio devices:", error);
      }
    };

    getAudioDevices();
  }, []);

  const setAudioInput = async (deviceId) => {
    try {
      if (currentStream) {
        currentStream.getTracks().forEach((track) => track.stop());
      }

      const stream = await navigator.mediaDevices.getUserMedia({
        audio: { deviceId: { exact: deviceId } },
      });
      setCurrentStream(stream);
      console.log("Current Stream:", stream);

      // Audio stream section
      // audioContext.createMediaStreamSource(stream);
    } catch (error) {
      console.error("Error setting audio input:", error);
    }
  };

  const handleInputChange = (event) => {
    const deviceId = event.target.value;
    setSelectedInput(deviceId);
    setAudioInput(deviceId);
  };

  return (
    <Box>
      <VStack spacing={4}>
        <Text>Select Audio Input:</Text>
        <Select
          value={selectedInput}
          onChange={handleInputChange}
          placeholder="Select microphone"
        >
          {audioInputs.map((input) => (
            <option key={input.deviceId} value={input.deviceId}>
              {input.label || `Microphone ${input.deviceId}`}
            </option>
          ))}
        </Select>
      </VStack>
    </Box>
  );
};

export default AudioInputSelector;