File size: 5,215 Bytes
811126d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"use client";

import { useEffect, useRef, useState } from "react";
import io from "socket.io-client";
import Peer from "simple-peer";

const socket = io("http://localhost:5001");

export default function VoiceCall() {
  const [stream, setStream] = useState<MediaStream | null>(null);
  const [peer, setPeer] = useState<Peer.Instance | null>(null);
  const [pitchShift, setPitchShift] = useState<number>(1);
  const myAudio = useRef<HTMLAudioElement>(null);
  const otherAudio = useRef<HTMLAudioElement>(null);
  const audioContextRef = useRef<AudioContext | null>(null);
  const sourceNodeRef = useRef<MediaStreamAudioSourceNode | null>(null);
  const pitchNodeRef = useRef<any>(null);

  const applyPitchEffect = (audioStream: MediaStream) => {
    if (!audioContextRef.current) {
      audioContextRef.current = new AudioContext();
    }
    const audioContext = audioContextRef.current;

    // Create source node
    sourceNodeRef.current = audioContext.createMediaStreamSource(audioStream);

    // Create ScriptProcessor for pitch shifting
    const bufferSize = 4096;
    pitchNodeRef.current = audioContext.createScriptProcessor(bufferSize, 1, 1);

    pitchNodeRef.current.onaudioprocess = (
      audioProcessingEvent: AudioProcessingEvent
    ) => {
      const inputBuffer = audioProcessingEvent.inputBuffer;
      const outputBuffer = audioProcessingEvent.outputBuffer;

      for (
        let channel = 0;
        channel < outputBuffer.numberOfChannels;
        channel++
      ) {
        const inputData = inputBuffer.getChannelData(channel);
        const outputData = outputBuffer.getChannelData(channel);

        // Simple pitch shift by resampling
        for (let i = 0; i < outputBuffer.length; i++) {
          const index = Math.floor(i * pitchShift);
          outputData[i] = index < inputBuffer.length ? inputData[index] : 0;
        }
      }
    };

    // Connect nodes
    sourceNodeRef.current.connect(pitchNodeRef.current);
    pitchNodeRef.current.connect(audioContext.destination);

    return new MediaStream([audioStream.getAudioTracks()[0]]);
  };

  useEffect(() => {
    navigator.mediaDevices
      .getUserMedia({
        audio: {
          echoCancellation: true,
          noiseSuppression: true,
          autoGainControl: true,
          sampleRate: 48000,
          channelCount: 2,
        },
      })
      .then((audioStream) => {
        const processedStream = applyPitchEffect(audioStream);
        setStream(processedStream);
        if (myAudio.current) {
          myAudio.current.srcObject = processedStream;
        }
      })
      .catch((err) => console.error("Audio error:", err));

    return () => {
      if (pitchNodeRef.current) {
        pitchNodeRef.current.disconnect();
      }
      if (sourceNodeRef.current) {
        sourceNodeRef.current.disconnect();
      }
      if (audioContextRef.current) {
        audioContextRef.current.close();
      }
    };
  }, []);

  const callUser = () => {
    if (!stream) return;
    const peer = new Peer({
      initiator: true,
      trickle: false,
      stream,
      config: {
        iceServers: [
          { urls: "stun:stun.l.google.com:19302" },
          { urls: "stun:global.stun.twilio.com:3478" },
        ],
      },
    });
    peer.on("signal", (data) => socket.emit("offer", data));
    peer.on("stream", (userStream) => {
      console.log("Received voice stream from peer");
      if (otherAudio.current) {
        otherAudio.current.srcObject = userStream;
        console.log("Successfully set remote audio stream");
      }
    });

    socket.on("answer", (answer) => {
      console.log("Received answer from remote peer");
      peer.signal(answer);
    });
    socket.on("candidate", (candidate) => {
      console.log("Received ICE candidate");
      peer.signal(candidate);
    });

    setPeer(peer);
  };

  const receiveCall = () => {
    if (!stream) return;
    const peer = new Peer({
      initiator: false,
      trickle: false,
      stream,
      config: {
        iceServers: [
          { urls: "stun:stun.l.google.com:19302" },
          { urls: "stun:global.stun.twilio.com:3478" },
        ],
      },
    });

    socket.on("offer", (offer) => {
      console.log("Received call offer");
      peer.signal(offer);
    });

    peer.on("signal", (data) => {
      console.log("Generated answer");
      socket.emit("answer", data);
    });

    peer.on("stream", (userStream) => {
      console.log("Received voice stream from caller");
      if (otherAudio.current) {
        otherAudio.current.srcObject = userStream;
        console.log("Successfully set remote audio stream");
      }
    });

    setPeer(peer);
  };

  return (
    <div>
      <audio ref={myAudio} autoPlay muted />
      <audio ref={otherAudio} autoPlay />
      <button onClick={callUser}>Call</button>
      <button onClick={receiveCall}>Receive Call</button>
      <div>
        <label>
          Pitch Shift:
          <input
            type="range"
            min="0.5"
            max="2"
            step="0.1"
            value={pitchShift}
            onChange={(e) => setPitchShift(Number(e.target.value))}
          />
        </label>
      </div>
    </div>
  );
}