Certainly! Below is a Python script that uses OpenAI's Whisper model to recognize a user's voice in real-time. It captures audio from the microphone, detects pauses in speech using a Voice Activity Detector (VAD), and transcribes the spoken words when a pause is detected.
Please note:
Here's the code:
import sounddevice as sd
import numpy as np
import queue
import threading
import time
import webrtcvad
import whisper
import sys
# Parameters
sample_rate = 16000 # Whisper expects audio at 16000 Hz
frame_duration = 30 # Frame size in ms for VAD
num_channels = 1 # Mono audio
max_pause_duration = 0.8 # Max duration of silence (in seconds) to consider as a pause
# Initialize Whisper model
print("Loading Whisper model...")
whisper_model = whisper.load_model("base") # Choose model size: tiny, base, small, medium, large
# Initialize VAD
vad = webrtcvad.Vad()
vad.set_mode(1) # Aggressiveness mode (0-3). Higher values are more aggressive.
# Audio queue for communication between callback and processing thread
audio_queue = queue.Queue()
# Flag to stop the processing thread
stop_flag = threading.Event()
def audio_callback(indata, frames, time_info, status):
"""Callback function called by sounddevice for each audio block."""
if status:
print(f"Recording error: {status}", file=sys.stderr)
# Store a copy of the audio data in the queue
audio_queue.put(indata.copy())
def process_audio():
"""Thread function to process audio blocks from the queue."""
audio_data = bytearray()
last_voice_time = time.time()
speech_active = False
while not stop_flag.is_set():
try:
# Wait for an audio block from the queue
indata = audio_queue.get(timeout=0.1)
except queue.Empty:
indata = None
if indata is not None:
# Convert audio block to 16-bit PCM
pcm_data = (indata * 32768).astype(np.int16)
pcm_bytes = pcm_data.tobytes()
# Split audio into frames for VAD
frame_size = int(sample_rate * frame_duration / 1000) * 2 # 2 bytes per sample (16-bit audio)
frames = [pcm_bytes[i:i + frame_size] for i in range(0, len(pcm_bytes), frame_size)]
for frame in frames:
if len(frame) < frame_size:
# Ignore incomplete frames
continue
is_speech = vad.is_speech(frame, sample_rate)
if is_speech:
audio_data.extend(frame)
last_voice_time = time.time()
speech_active = True
else:
if speech_active and (time.time() - last_voice_time > max_pause_duration):
# Detected pause in speech
print("Transcribing...")
# Convert accumulated audio to numpy array
audio_np = np.frombuffer(audio_data, np.int16).astype(np.float32) / 32768.0
# Transcribe with Whisper
result = whisper_model.transcribe(audio_np, language='en')
print(f"You said: {result['text']}\n")
# Reset for next utterance
audio_data = bytearray()
speech_active = False
else:
# No data received; check for silence after speech
if speech_active and (time.time() - last_voice_time > max_pause_duration):
print("Transcribing...")
audio_np = np.frombuffer(audio_data, np.int16).astype(np.float32) / 32768.0
result = whisper_model.transcribe(audio_np, language='en')
print(f"You said: {result['text']}\n")
audio_data = bytearray()
speech_active = False
# Process any remaining audio data when stopping
if audio_data:
print("Final transcribing...")
audio_np = np.frombuffer(audio_data, np.int16).astype(np.float32) / 32768.0
result = whisper_model.transcribe(audio_np, language='en')
print(f"You said: {result['text']}\n")
def main():
try:
# Start audio stream
with sd.InputStream(callback=audio_callback,
channels=num_channels,
samplerate=sample_rate,
blocksize=int(sample_rate * frame_duration / 1000),
dtype='float32'):
print("Listening... Press Ctrl+C to stop.")
# Start audio processing thread
threading.Thread(target=process_audio, daemon=True).start()
# Keep the main thread alive
while True:
time.sleep(0.1)
except KeyboardInterrupt:
print("\nStopping...")
stop_flag.set()
sys.exit()
if __name__ == "__main__":
main()
How the Code Works:
Adjustments You Can Make:
- Model Size: Change the model loaded by Whisper to
'tiny', 'base', 'small', 'medium', or 'large' depending on your accuracy and performance needs.
whisper_model = whisper.load_model("base")
- VAD Sensitivity: Adjust the VAD aggressiveness mode (0 to 3). Higher values make the VAD more aggressive in filtering out non-speech, which might help in noisy environments.
vad.set_mode(1)
- Pause Duration: Modify
max_pause_duration to change how long a silence should be to be considered a pause.
max_pause_duration = 0.8 # in seconds
- Language: Set the
language parameter in transcribe if you're recognizing languages other than English.
result = whisper_model.transcribe(audio_np, language='en')
Run the Script:
- Save the code to a file, e.g.,
realtime_whisper.py.
- Install the required packages if you haven't already.
- Run the script:
python realtime_whisper.py
- Start speaking, and after you pause, the script will transcribe and display what you said.
Troubleshooting:
- Microphone Issues: Ensure that your microphone is properly set up and selected as the default input device.
- Performance: If you experience delays, try using a smaller Whisper model or check your system's resource usage.
- Dependencies: If you encounter installation issues with packages like
webrtcvad, ensure you have the necessary build tools and libraries installed on your system.
Let me know if you have any questions or need further assistance!