SCALE — Build Lab
機能パターン · REACT COMPONENT

音声録音(MediaRecorder)

CATEGORY機能パターン TYPEReact Component EFFORT60〜120分 DIFFICULTY
PRIMARY CODE
ts
export class AudioRecorder {
  private recorder: MediaRecorder | null = null;
  private chunks: Blob[] = [];

  async start() {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    this.recorder = new MediaRecorder(stream);
    this.chunks = [];
    this.recorder.ondataavailable = (e) => this.chunks.push(e.data);
    this.recorder.start();
  }

  stop(): Promise<Blob> {
    return new Promise(resolve => {
      this.recorder!.onstop = () => {
        resolve(new Blob(this.chunks, { type: 'audio/webm' }));
        this.recorder!.stream.getTracks().forEach(t => t.stop());
      };
      this.recorder!.stop();
    });
  }
}
前提条件
Tailwind CSS v4TypeScript 5
USE CASES
  • 任意のダッシュボードに組み込み

音声録音(MediaRecorder)

:LiTarget: 用途

ブラウザで音声録音 → Blobで保存・送信。議事録・音声メモに。

:LiSparkle: 特徴

  • 録音/停止
  • リアルタイム波形表示
  • Blob出力
  • WAV変換

:LiCode: コード(コピペ用)

export class AudioRecorder {
  private recorder: MediaRecorder | null = null;
  private chunks: Blob[] = [];

  async start() {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    this.recorder = new MediaRecorder(stream);
    this.chunks = [];
    this.recorder.ondataavailable = (e) => this.chunks.push(e.data);
    this.recorder.start();
  }

  stop(): Promise<Blob> {
    return new Promise(resolve => {
      this.recorder!.onstop = () => {
        resolve(new Blob(this.chunks, { type: 'audio/webm' }));
        this.recorder!.stream.getTracks().forEach(t => t.stop());
      };
      this.recorder!.stop();
    });
  }
}

:LiHandPointer: 使い方

対象プロジェクトに該当ファイルをコピーして、props を流し込むだけ。

:LiAlertCircle: 注意事項

  • 依存パッケージを忘れず追加