使用 Python 建立語音錄音機



在這裡,我們將使用 Python 建立一個應用程式(語音錄音機),允許使用者錄製語音。我們將使用 sounddevice 庫和 Python 建立此語音錄音機應用程式。

使用語音錄音機,您可以啟動錄製過程、暫停它或在必要時取消。錄製的聲音儲存為兩種格式 WAV 和 WAVIO。此語音錄音機應用程式可用於只需要簡單音訊錄製和回放的應用程式。

所需庫

要在 Python 中建立語音錄音機,以下為所需的庫:

  • sounddevice - sounddevice 庫將用於捕獲音訊。
  • scipy - 此庫將用於使用 write 函式寫入 WAV 檔案。
  • wavio - 此庫將用於使用其他選項寫入 wav 檔案。
  • numpy - 此庫將用於矩陣或陣列計算。

安裝

要安裝建立語音記錄所需的庫,您需要使用 PIP 安裝這些庫。使用以下語句一次安裝所有所需的庫:

pip install sounddevice scipy wavio numpy

建立語音錄音機的步驟

1. 匯入庫

安裝完成後,您需要在程式碼中匯入所有庫。要匯入所需的庫,請使用以下程式碼語句:

import sounddevice as sd
from scipy.io.wavfile import write
import wavio as wv
import numpy as np
import threading

步驟 2:初始化變數

使用以下程式碼設定取樣頻率和用於管理錄製狀態的標誌:

  • 設定取樣頻率:
freq = 44100
  • 儲存錄製的音訊片段:
recording = []
  • 設定預設標誌值以檢查錄製是否處於活動狀態:
is_recording = False
  • 設定預設標誌值以停止錄製:
stop_recording = False

步驟 3:定義錄製函式

建立一個函式來處理迴圈中的音訊錄製,並將每個片段追加到錄製列表中。使用以下程式碼:

def record_audio():
   global recording, is_recording, stop_recording
   is_recording = True
   while is_recording and not stop_recording:
      recording_segment = sd.rec(int(freq), samplerate=freq, channels=2)
      sd.wait()  # Wait until the recording is finished
      recording.append(recording_segment)

步驟 4:定義輸入處理函式

實現一個函式來處理用於錄製控制(開始、暫停、停止)的使用者命令。使用以下程式碼:

def handle_input():
   global is_recording, stop_recording
   while True:
      user_input = input("r to START , p to PAUSE and s to STOP the recording, please choice accordingly \n Enter command: ").lower()
      if user_input == 'p':
         if is_recording:
            print("Recording Paused, (you can again start the recording using 'r')")
            is_recording = False
         else:
            print("Recording is not active.")
      elif user_input == 'r':
         if not is_recording:
            print("Recording Resumed (type 'p' to pause or 's' to stop)")
            threading.Thread(target=record_audio).start()
         else:
            print("Already recording.")
      elif user_input == 's':
         if is_recording:
            print("Stopping recording. Thank you for recording :)")
            is_recording = False
            stop_recording = True
            break
         else:
            print("Nothing to stop.")

步驟 5:組合並保存錄制

停止錄製後,將所有錄製片段組合成一個音訊檔案,並將其儲存為不同的格式。使用以下程式碼:

if recording:
   final_recording = np.concatenate(recording, axis=0)
   write("recording0.wav", freq, final_recording)
   wv.write("recording1.wav", final_recording, freq, sampwidth=2)
   print("Recording saved as 'recording0.wav' and 'recording1.wav'.")
else:
   print("No recording was made.")

建立語音錄音機的 Python 程式碼

以下是使用 Python 建立語音錄音機應用程式的完整程式碼:

import sounddevice as sd
from scipy.io.wavfile import write
import wavio as wv
import numpy as np
import threading
# Sampling frequency
freq = 44100

# Initialize recording variables
recording = []
is_recording = False
stop_recording = False

def record_audio():
   global recording, is_recording, stop_recording
   is_recording = True
   while is_recording and not stop_recording:
      recording_segment = sd.rec(int(freq), samplerate=freq, channels=2)
      sd.wait()
      recording.append(recording_segment)

def handle_input():
   global is_recording, stop_recording
   while True:
      user_input = input("r to START , p to PAUSE and s to STOP the recording, please choice accordingly \n Enter command: ").lower()
      if user_input == 'p':
         if is_recording:
            print("Recording Paused, (you can again start the recording using 's') ")
            is_recording = False
         else:
            print("Recording is not working activly.")
      elif user_input == 'r':
         if not is_recording:
            print("Recording Resumed (type 'p' to pause or 's' to stop)")
            threading.Thread(target=record_audio).start()
         else:
            print("Already recording.")
      elif user_input == 's':
         if is_recording:
            print("Stopping recording. Thank you for recording :) ")
            is_recording = False
            stop_recording = True
            break
         else:
            print(" Nothing to stop.")

# Start the input handler in a separate thread
input_thread = threading.Thread(target=handle_input)
input_thread.start()

# Wait for the input thread to complete
input_thread.join()

# Combine all the recorded segments
if recording:
   final_recording = np.concatenate(recording, axis=0)
   write("recording0.wav", freq, final_recording)
   wv.write("recording1.wav", final_recording, freq, sampwidth=2)
   print("Recording saved as 'recording0.wav' and 'recording1.wav'.")
else:
   print("No recording was made.")

輸出

執行此程式碼後,您將看到按下“r”鍵開始錄製,“p”鍵暫停,“s”鍵停止錄製。

Voice Recorder

現在您還可以在您的電腦上看到錄製的音訊檔案。

Voice Recorder

之後,您就可以成功收聽您的音訊檔案了。

Voice Recorder

程式碼解釋

  • **匯入庫** - 匯入用於錄製和處理音訊以及管理音訊檔案的庫。
  • **初始化變數** - 應設定“取樣率”、“錄製列表”和“標誌”作為錄製控制引數。
  • **定義 record_audio 函式** - 錄製音訊片段並將其新增到列表中。
  • **定義 handle_input 函式** - 操作使用者開始或停止錄製過程的指令。
  • **啟動輸入處理執行緒** - 線上程中管理輸入處理函式,以避免遊戲凍結。
  • **等待輸入執行緒完成** - 在繼續執行主執行緒的後續操作之前,等待輸入執行緒完成執行。
  • **合併錄製片段** - 將所有錄製的音訊片段組合成一個軌道或稱為片段。
  • **以 WAV 格式保存錄制** - 透過兩種方法將組合後的音訊儲存為 WAV 檔案。
  • **列印完成訊息** - 讓使用者知道錄製已成功儲存。
  • **處理無錄製場景** - 如果未錄製任何音訊,則發出警報。
python_reference.htm
廣告