Here's a simple Python script to capture microphone input and transcribe it using Whisper:
import whisper
import pyaudio
import wave
import tempfile
import os
# Load the Whisper model (you can choose different sizes: tiny, base, small, medium, large)
model = whisper.load_model("base")
# Set up audio parameters
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
CHUNK = 1024
RECORD_SECONDS = 5 # Adjust recording duration as needed
# Initialize PyAudio
audio = pyaudio.PyAudio()
def record_audio():
print("Recording... Speak now")
# Start recording
stream = audio.open(format=FORMAT, channels=CHANNELS,
rate=RATE, input=True,
frames_per_buffer=CHUNK)
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("Recording finished")
# Stop recording
stream.stop_stream()
stream.close()
# Save as temporary WAV file
with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_audio:
temp_filename = temp_audio.name
wf = wave.open(temp_filename, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
return temp_filename
def transcribe_audio(audio_file):
# Transcribe audio using Whisper
result = model.transcribe(audio_file, language="en")
return result["text"]
try:
while True:
input("Press Enter to start recording (Ctrl+C to exit)...")
audio_file = record_audio()
print("Transcribing...")
transcription = transcribe_audio(audio_file)
print("\nTranscription:")
print(transcription)
# Clean up temporary file
os.unlink(audio_file)
except KeyboardInterrupt:
print("\nExiting program")
audio.terminate()
Would you like me to explain or break down this code?