Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                #root
              
            
!

CSS

              
                .App {
  font-family: sans-serif;
  text-align: center;
}

* {
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  display: grid;
  place-items: center;
}
              
            
!

JS

              
                const { XState, XStateReact, React, ReactDOM } = window

const { createMachine, assign, send: sendUtil } = XState
const { useMachine } = XStateReact

function assertNonNull<PossibleNullType>(
  possibleNull: PossibleNullType,
  errorMessage: string
): asserts possibleNull is Exclude<PossibleNullType, null> {
  if (possibleNull === null) throw new Error(errorMessage);
}

const devTools = false;

// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (devTools && typeof window !== "undefined") {
  inspect({ iframe: false });
}

function stopMediaRecorder(mediaRecorder: MediaRecorder) {
  if (mediaRecorder.state !== "inactive") mediaRecorder.stop();

  for (const track of mediaRecorder.stream.getAudioTracks()) {
    if (track.enabled) track.stop();
  }
  mediaRecorder.ondataavailable = null;
}

interface RecorderContext {
  mediaRecorder: MediaRecorder | null;
  audioDevices: Array<MediaDeviceInfo>;
  selectedAudioDevice: MediaDeviceInfo | null;
  audioBlob: Blob | null;
}

const recorderMachine = createMachine<RecorderContext>(
  {
    id: "recorder",
    context: {
      mediaRecorder: null,
      audioDevices: [],
      selectedAudioDevice: null,
      audioBlob: null
    },
    initial: "gettingDevices",
    states: {
      gettingDevices: {
        invoke: {
          src: "getDevices",
          onDone: { target: "ready", actions: "assignAudioDevices" },
          onError: "" // TODO
        }
      },
      selecting: {
        on: {
          selection: { target: "ready", actions: "assignSelectedAudioDevice" }
        }
      },
      ready: {
        on: {
          changeDevice: "selecting",
          start: "recording"
        }
      },
      recording: {
        invoke: { src: "mediaRecorder" },
        initial: "playing",
        states: {
          playing: {
            on: {
              mediaRecorderCreated: {
                actions: ["assignMediaRecorder"]
              },
              pause: {
                target: "paused",
                actions: sendUtil("pause", { to: "mediaRecorder" })
              },
              stop: "stopping"
            }
          },
          paused: {
            on: {
              resume: {
                target: "playing",
                actions: sendUtil("resume", { to: "mediaRecorder" })
              },
              stop: "stopping"
            }
          },
          stopping: {
            entry: sendUtil("stop", { to: "mediaRecorder" }),
            on: {
              chunks: { target: "#recorder.done", actions: "assignAudioBlob" }
            }
          }
        }
      },
      done: {
        on: {
          restart: "ready"
        }
      }
    }
  },
  {
    services: {
      getDevices: async () => {
        const devices = await navigator.mediaDevices.enumerateDevices();
        return devices.filter(({ kind }) => kind === "audioinput");
      },
      mediaRecorder: (context) => (sendBack, receive) => {
        let mediaRecorder: MediaRecorder;

        async function go() {
          const chunks: Array<BlobPart> = [];
          const deviceId = context.selectedAudioDevice?.deviceId;
          const audio = deviceId ? { deviceId: { exact: deviceId } } : true;
          const mediaStream = await window.navigator.mediaDevices.getUserMedia({
            audio
          });
          mediaRecorder = new MediaRecorder(mediaStream);
          sendBack({ type: "mediaRecorderCreated", mediaRecorder });

          mediaRecorder.ondataavailable = (event) => {
            chunks.push(event.data);
            console.info('running')
            if (mediaRecorder.state === "inactive") {
              sendBack({
                type: "chunks",
                blob: new Blob(chunks, {
                  type: "audio/mp3"
                })
              });
            }
          };

          mediaRecorder.start();

          receive((event) => {
            if (event.type === "pause") {
              mediaRecorder.pause();
            } else if (event.type === "resume") {
              mediaRecorder.resume();
            } else if (event.type === "stop") {
              mediaRecorder.stop();
            }
          });
        }

        void go();

        return () => {
          stopMediaRecorder(mediaRecorder);
        };
      }
    },
    actions: {
      assignAudioDevices: assign({
        audioDevices: (context, event) => event.data
      }),
      assignSelectedAudioDevice: assign({
        selectedAudioDevice: (context, event) => event.selectedAudioDevice
      }),
      assignMediaRecorder: assign({
        mediaRecorder: (context, event) => event.mediaRecorder
      }),
      assignAudioBlob: assign({
        audioBlob: (context, event) => event.blob
      })
    }
  }
);

function CallRecorder({
  onRecordingComplete
}: {
  onRecordingComplete: (audio: Blob) => void;
}) {
  const [state, send] = useMachine(recorderMachine, { devTools });
  const { audioBlob } = state.context;

  const audioURL = React.useMemo(() => {
    if (audioBlob) {
      return window.URL.createObjectURL(audioBlob);
    } else {
      return null;
    }
  }, [audioBlob]);

  let deviceSelection = null;
  if (state.matches("gettingDevices")) {
    deviceSelection = <div>Loading devices</div>;
  }

  if (state.matches("selecting")) {
    deviceSelection = (
      <div>
        Select your device:
        <ul>
          {state.context.audioDevices.length
            ? state.context.audioDevices.map((device) => (
                <li key={device.deviceId}>
                  <button
                    onClick={() => {
                      send({
                        type: "selection",
                        selectedAudioDevice: device
                      });
                    }}
                    style={{
                      fontWeight:
                        state.context.selectedAudioDevice === device
                          ? "bold"
                          : "normal"
                    }}
                  >
                    {device.label}
                  </button>
                </li>
              ))
            : "No audio devices found"}
        </ul>
      </div>
    );
  }

  let audioPreview = null;
  if (state.matches("done")) {
    assertNonNull(
      audioURL,
      `The state machine is in "stopped" state but there's no audioURL. This should be impossible.`
    );
    assertNonNull(
      audioBlob,
      `The state machine is in "stopped" state but there's no audioBlob. This should be impossible.`
    );
    audioPreview = (
      <div>
        <audio src={audioURL} controls />
        <button onClick={() => onRecordingComplete(audioBlob)}>Accept</button>
        <button onClick={() => send({ type: "restart" })}>Re-record</button>
      </div>
    );
  }

  return (
    <div>
      {state.matches("ready") ? (
        <button onClick={() => send({ type: "changeDevice" })}>
          Change audio device from{" "}
          {state.context.selectedAudioDevice?.label ?? "default"}
        </button>
      ) : null}
      {deviceSelection}
      {state.matches("ready") ? (
        <button onClick={() => send({ type: "start" })}>Start</button>
      ) : null}
      {state.matches("recording") && state.context.mediaRecorder ? (
        <StreamVis stream={state.context.mediaRecorder.stream} />
      ) : null}
      {state.matches("recording.playing") ? (
        <>
          <button onClick={() => send({ type: "stop" })}>Stop</button>
          <button onClick={() => send({ type: "pause" })}>Pause</button>
        </>
      ) : state.matches("recording.paused") ? (
        <>
          <button onClick={() => send({ type: "stop" })}>Stop</button>
          <button onClick={() => send({ type: "resume" })}>Resume</button>
        </>
      ) : state.matches("recording.stopping") ? (
        <div>Processing...</div>
      ) : null}
      {audioPreview}
    </div>
  );
}

function visualize(canvas: HTMLCanvasElement, stream: MediaStream) {
  const audioCtx = new AudioContext();
  const canvasCtx = canvas.getContext("2d");

  const source = audioCtx.createMediaStreamSource(stream);

  const analyser = audioCtx.createAnalyser();
  analyser.fftSize = 2048;
  const bufferLength = analyser.frequencyBinCount;
  const dataArray = new Uint8Array(bufferLength);

  source.connect(analyser);

  function draw() {
    if (!canvasCtx) return;
    const WIDTH = canvas.width;
    const HEIGHT = canvas.height;

    analyser.getByteTimeDomainData(dataArray);

    canvasCtx.fillStyle = "rgb(180, 180, 180)";
    canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

    canvasCtx.lineWidth = 2;
    canvasCtx.strokeStyle = "rgb(0, 0, 0)";

    canvasCtx.beginPath();

    const sliceWidth = (WIDTH * 1.0) / bufferLength;
    let x = 0;

    for (let i = 0; i < bufferLength; i++) {
      const v = (dataArray[i] ?? 0) / 128.0;
      const y = (v * HEIGHT) / 2;

      if (i === 0) {
        canvasCtx.moveTo(x, y);
      } else {
        canvasCtx.lineTo(x, y);
      }

      x += sliceWidth;
    }

    canvasCtx.lineTo(canvas.width, canvas.height / 2);
    canvasCtx.stroke();
  }

  return draw;
}

function StreamVis({ stream }: { stream: MediaStream }) {
  const canvasRef = React.useRef<HTMLCanvasElement | null>(null);

  React.useEffect(() => {
    if (!canvasRef.current) return () => {};
    const draw = visualize(canvasRef.current, stream);
    let lastReq: number;
    function reqDraw() {
      lastReq = requestAnimationFrame(() => {
        draw();
        reqDraw();
        // TODO: this happens too frequently...
      });
    }
    reqDraw();
    return () => {
      cancelAnimationFrame(lastReq);
    };
  }, [stream]);
  return <canvas ref={canvasRef} />;
}

ReactDOM.render(
  <CallRecorder
    onRecordingComplete={(...args) => console.log("complete", ...args)}
  />,
  document.getElementById("root")
);

              
            
!
999px

Console