如何在JavaScript中錄製和播放音訊?


您是否也希望在您的Web應用程式中新增自定義音訊錄製功能?如果是,那麼您來對地方了,因為在本教程中,我們將學習如何使用JavaScript錄製和播放音訊。

一些應用程式,例如Discord,允許您錄製音訊並將其儲存在其中,以便隨時播放。錄製的音訊也可以用作有趣的模因、Discord會議中的警報等。

我們還可以使用JavaScript的MediaRecorder API將音訊錄製功能新增到我們的Web應用程式中。在這裡,我們將學習一個逐步指導,講解如何錄製、儲存和播放音訊。

語法

使用者可以按照以下語法使用MediaRecorder API錄製和播放音訊。

navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
   audioRecorder = new MediaRecorder(stream);
   audioRecorder.start();
   audioRecorder.stop();
   const blobObj = new Blob(audioChunks, { type: 'audio/webm' });
   const audioUrl = URL.createObjectURL(blobObj);
   const audio = new Audio(audioUrl);
   audio.play();
})

引數和方法解釋

  • Navigator.mediaDevice − mediaDevice物件提供對媒體相關功能(例如音訊和影片流)的訪問。

  • getUserMedia() − getUserMedia()方法請求使用者對媒體流的許可權。它接受包含媒體流型別的物件作為引數。在這裡,我們使用{ audio : true }來訪問音訊流並請求麥克風的許可權。

  • Stream − 我們將其作為回撥函式的引數傳遞,該函式在使用者批准許可權後獲得。

  • MediaRecorder − 我們可以透過將流變數作為引數傳遞給MediaRecorder()建構函式來建立一個新的媒體錄製器。

  • Start() − 用於開始錄製。

  • Stop() − 用於停止錄製。

  • Blob() − 用於將音訊塊轉換為Blob物件。

  • createObjectURL() − 它從Blob物件建立音訊URL。

  • Audio() − 它將音訊URL轉換為音訊。

  • Play() − 用於播放音訊URL。

示例

我們在下面的示例中添加了開始、停止和播放錄製按鈕。在JavaScript中,我們訪問使用者裝置的媒體流,然後使用媒體流初始化媒體錄製器物件。

接下來,我們根據單擊的按鈕呼叫方法並將錄製器音訊儲存在“audioChunks”陣列中。此外,我們還使用catch()塊來捕獲錄製音訊時的錯誤。

在輸出中,使用者可以單擊“開始錄製”按鈕開始錄製。錄製完成後,單擊“停止錄製”按鈕。接下來,單擊“播放錄製”按鈕播放錄製的音訊。

<html>
<head>
   <style>
      button {margin: 5px; padding: 10px 20px; background-color: #007bff; color: #fff; border: none; border-radius: 5px; cursor: pointer;}
      button:hover {background-color: #0056b3;}
      div { margin-top: 20px;}
   </style>
</head>
<body>
   <h3> Using the Media recorder API to record the audio in the web browser </h3>
   <div>
      <button id = "start"> Start Recording </button>
      <button id = "stop"> Stop Recording </button>
      <button id = "play"> Play Recorded Audio </button>
   </div> <br> 
   <div id = "output"> </div>
   <script>
      const startButton = document.getElementById('start');
      const stopButton = document.getElementById('stop');
      const playButton = document.getElementById('play');
      let output = document.getElementById('output');
      let audioRecorder;
      let audioChunks = [];
      navigator.mediaDevices.getUserMedia({ audio: true })
         .then(stream => {
         
            // Initialize the media recorder object
            audioRecorder = new MediaRecorder(stream);
            
            // dataavailable event is fired when the recording is stopped
            audioRecorder.addEventListener('dataavailable', e => {
               audioChunks.push(e.data);
            });
            
            // start recording when the start button is clicked
            startButton.addEventListener('click', () => {
               audioChunks = [];
               audioRecorder.start();
               output.innerHTML = 'Recording started! Speak now.';
            });
            
            // stop recording when the stop button is clicked
            stopButton.addEventListener('click', () => {
               audioRecorder.stop();
               output.innerHTML = 'Recording stopped! Click on the play button to play the recorded audio.';
            });
            
            // play the recorded audio when the play button is clicked
            playButton.addEventListener('click', () => {
               const blobObj = new Blob(audioChunks, { type: 'audio/webm' });
               const audioUrl = URL.createObjectURL(blobObj);
               const audio = new Audio(audioUrl);
               audio.play();
               output.innerHTML = 'Playing the recorded audio!';
            });
         }).catch(err => {
         
            // If the user denies permission to record audio, then display an error.
            console.log('Error: ' + err);
         });
   </script>
</body>
</html>

在本教程中,使用者學習瞭如何使用MediaRecorder API錄製媒體。開發人員可以允許使用者錄製音訊並將其儲存在本地儲存中,以便使用者即使在重新載入網頁後也可以重複播放錄製的音訊。

更新於:2023年7月26日

4K+ 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.