Sure! If you want to avoid using the Google Speech Recognition API, you can use the vosk API, which provides free and offline speech recognition. Below is how you can implement your requirement using the Vosk Speech Recognition library.
Requirements
- Vosk: You will need the Vosk library for speech recognition.
- PyAudio: It is still needed for audio capture.
- Vosk Model: You will need to download a Vosk model for English.
You can install the necessary libraries using pip:
pip install pyaudio vosk
Download a Vosk Model
You can download a Vosk English model from the official Vosk GitHub repository. Here’s how to do it:
- Visit the Vosk Models Page.
- Download the “small” English model, which is about 50MB.
- Unzip the downloaded model into a directory, e.g.,
vosk-model-small-en-us-0.15.
Updated Python Script
Here’s an example of how to record audio from both the microphone and the speaker, and then transcribe it using the Vosk library:
import wave
import pyaudio
import os
import json
from vosk import Model, KaldiRecognizer
# Function to record audio from the microphone
def record_audio(filename, record_seconds=10):
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
CHUNK = 1024
audio = pyaudio.PyAudio()
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
print(f"Recording audio for {record_seconds} seconds...")
frames = []
for _ in range(0, int(RATE / CHUNK * record_seconds)):
data = stream.read(CHUNK)
frames.append(data)
print("Finished recording audio.")
stream.stop_stream()
stream.close()
audio.terminate()
# Save the audio to a file
with wave.open(filename, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
# Function to transcribe audio to text using Vosk
def transcribe_audio(filename, model):
with wave.open(filename, "rb") as wf:
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True) # Optional: Set to report words as they are recognized
results = []
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
results.append(rec.Result())
else:
results.append(rec.PartialResult())
results.append(rec.FinalResult())
# Combine results into a single string
transcript = ""
for result in results:
json_result = json.loads(result)
if 'text' in json_result:
transcript += json_result['text'] + " "
return transcript.strip()
# Main function to run recording and transcription
def main():
model_path = "vosk-model-small-en-us-0.15" # Update the path to your model
if not os.path.exists(model_path):
print(f"Please download the Vosk model and unzip it to {model_path}")
return
model = Model(model_path)
# Record microphone audio
mic_filename = "microphone_audio.wav"
record_audio(mic_filename, record_seconds=10)
mic_transcript = transcribe_audio(mic_filename, model)
print("Microphone Transcript:")
print(mic_transcript)
# Record speaker audio (You would need a loopback device setup for this)
speaker_filename = "speaker_audio.wav"
record_audio(speaker_filename, record_seconds=10)
speaker_transcript = transcribe_audio(speaker_filename, model)
print("Speaker Transcript:")
print(speaker_transcript)
if __name__ == "__main__":
main()
Notes:
- Replace
vosk-model-small-en-us-0.15 with the path to the model you downloaded.
- This script records audio from the microphone. For speaker audio, you'll need to ensure that your system is set up to capture audio played through the speakers (often done using a software audio routing tool).
- The
record_seconds parameter can be adjusted to record the desired length.
- Ensure that your microphone is working correctly, and remember that setup for capturing speaker audio may require further configuration depending on your OS and existing audio setup.
Setup for Speaker Audio:
For capturing speaker audio, you can use software like Voicemeeter on Windows to create a virtual audio device that can route speaker output back into an input that the script can record from, or you may use loopback features available in some audio interfaces or operating systems. On MacOS, you might consider using tools like BlackHole or Soundflower.