LoginSignup
0
0

Javascriptによるレコーディングアプリ

Last updated at Posted at 2023-10-18

Javascriptによるレコーディングアプリです。

録音アプリケーション

録音アプリケーション

録音開始 録音停止 再生 ダウンロード
<script>
    // 録音用変数
    let audioContext;
    let audioStream;
    let audioRecorder;

    // レコーディング開始ボタンのクリックハンドラ
    document.getElementById('startRecord').addEventListener('click', () => {
        navigator.mediaDevices.getUserMedia({ audio: true })
            .then(stream => {
                audioStream = stream;
                audioContext = new AudioContext();
                audioRecorder = new MediaRecorder(audioStream);

                const chunks = [];
                audioRecorder.ondataavailable = event => chunks.push(event.data);

                audioRecorder.onstop = () => {
                    const audioBlob = new Blob(chunks, { type: 'audio/wav' });
                    const audioUrl = URL.createObjectURL(audioBlob);
                    const audioDownloadLink = document.getElementById('downloadLink');
                    audioDownloadLink.href = audioUrl;
                    audioDownloadLink.download = 'recorded.wav';
                    audioDownloadLink.style.display = 'block';
                };

                audioRecorder.start();
                document.getElementById('startRecord').disabled = true;
                document.getElementById('stopRecord').disabled = false;
                document.getElementById('playRecord').disabled = true;
            })
            .catch(error => {
                console.error('録音の許可が拒否されました: ' + error);
            });
    });

    // 録音停止ボタンのクリックハンドラ
    document.getElementById('stopRecord').addEventListener('click', () => {
        audioRecorder.stop();
        audioStream.getTracks()[0].stop();
        document.getElementById('startRecord').disabled = false;
        document.getElementById('stopRecord').disabled = true;
        document.getElementById('playRecord').disabled = false;
    });

    // 再生ボタンのクリックハンドラ
    document.getElementById('playRecord').addEventListener('click', () => {
        const audioUrl = URL.createObjectURL(new Blob(audioRecorder.recordedChunks, { type: 'audio/wav' }));
        const audioElement = new Audio(audioUrl);
        audioElement.play();
    });
</script>
このコードの概要:

ユーザーにマイクのアクセス許可を要求するためにgetUserMediaを使用して録音ストリームを取得します。
MediaRecorderを使用して録音を開始、停止し、録音したデータをバッファに保存します。
レコーディングが終了すると、録音データをBlobに変換し、ダウンロードリンクを表示します。
録音、停止、再生ボタンのクリックハンドラを設定して、それぞれのアクションを実行します。
このコードはシンプルな例であり、録音アプリケーションをカスタマイズおよび拡張する際にはセキュリティとユーザー体験を考慮する必要があります。録音の品質やフォーマット、エラーハンドリング、UI/UXの向上などを追加することができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0