Skip to content

examples.mic_realtime

Real-Time Microphone Transcription with Whisper - vllm-mlx Transcribes speech in real-time as you speak using your Mac's microphone.

View the complete module source at #L1-L236.

API details

Each callable below includes its exact signature, type annotations, inputs, defaults, return contract, documented exceptions, implementation source, and parsed docstring sections when the source provides them.

examples.mic_realtime

Real-Time Microphone Transcription with Whisper - vllm-mlx

Transcribes speech in real-time as you speak using your Mac's microphone.

Usage

python examples/mic_realtime.py # Default (3s chunks) python examples/mic_realtime.py --chunk 5 # 5 second chunks python examples/mic_realtime.py --model parakeet # Faster model

Requirements

pip install sounddevice soundfile numpy

examples.mic_realtime.MODEL_ALIASES module-attribute

MODEL_ALIASES = {'whisper-large-v3': 'mlx-community/whisper-large-v3-mlx', 'whisper-turbo': 'mlx-community/whisper-large-v3-turbo', 'whisper-medium': 'mlx-community/whisper-medium-mlx', 'whisper-small': 'mlx-community/whisper-small-mlx', 'parakeet': 'mlx-community/parakeet-tdt-0.6b-v2', 'parakeet-v3': 'mlx-community/parakeet-tdt-0.6b-v3'}

examples.mic_realtime.SAMPLE_RATE module-attribute

SAMPLE_RATE = 16000

examples.mic_realtime.CHANNELS module-attribute

CHANNELS = 1

examples.mic_realtime.RealtimeTranscriber

RealtimeTranscriber(model_name: str, chunk_duration: float = 3.0, language: str = None)

Real-time audio transcription using Whisper.

Source code in examples/mic_realtime.py
def __init__(self, model_name: str, chunk_duration: float = 3.0, language: str = None):
    self.model_name = model_name
    self.chunk_duration = chunk_duration
    self.language = language
    self.sample_rate = SAMPLE_RATE

    # Audio buffer
    self.audio_queue = queue.Queue()
    self.is_recording = False

    # Transcription
    self.engine = None
    self.transcriptions = []

examples.mic_realtime.RealtimeTranscriber.model_name instance-attribute

model_name = model_name

examples.mic_realtime.RealtimeTranscriber.chunk_duration instance-attribute

chunk_duration = chunk_duration

examples.mic_realtime.RealtimeTranscriber.language instance-attribute

language = language

examples.mic_realtime.RealtimeTranscriber.sample_rate instance-attribute

sample_rate = SAMPLE_RATE

examples.mic_realtime.RealtimeTranscriber.audio_queue instance-attribute

audio_queue = queue.Queue()

examples.mic_realtime.RealtimeTranscriber.is_recording instance-attribute

is_recording = False

examples.mic_realtime.RealtimeTranscriber.engine instance-attribute

engine = None

examples.mic_realtime.RealtimeTranscriber.transcriptions instance-attribute

transcriptions = []

examples.mic_realtime.RealtimeTranscriber.load_model

load_model()

Load the STT model.

Source code in examples/mic_realtime.py
def load_model(self):
    """Load the STT model."""
    from vllm_mlx.audio.stt import STTEngine
    print(f"Loading model: {self.model_name}")
    self.engine = STTEngine(self.model_name)
    self.engine.load()
    print("Model ready!")

examples.mic_realtime.RealtimeTranscriber.audio_callback

audio_callback(indata, frames, time_info, status)

Callback for audio input stream.

Source code in examples/mic_realtime.py
def audio_callback(self, indata, frames, time_info, status):
    """Callback for audio input stream."""
    if status:
        print(f"Audio status: {status}")
    if self.is_recording:
        self.audio_queue.put(indata.copy())

examples.mic_realtime.RealtimeTranscriber.transcribe_chunk

transcribe_chunk(audio_data)

Transcribe a chunk of audio.

Source code in examples/mic_realtime.py
def transcribe_chunk(self, audio_data):
    """Transcribe a chunk of audio."""
    import soundfile as sf

    # Save to temp file
    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
        temp_path = f.name
    sf.write(temp_path, audio_data, self.sample_rate)

    try:
        result = self.engine.transcribe(temp_path, language=self.language)
        return result.text.strip()
    finally:
        os.unlink(temp_path)

examples.mic_realtime.RealtimeTranscriber.process_audio

process_audio()

Process audio chunks in real-time.

Source code in examples/mic_realtime.py
def process_audio(self):
    """Process audio chunks in real-time."""
    chunk_samples = int(self.chunk_duration * self.sample_rate)
    buffer = np.array([], dtype=np.float32)

    while self.is_recording or not self.audio_queue.empty():
        try:
            # Get audio from queue
            data = self.audio_queue.get(timeout=0.1)
            buffer = np.concatenate([buffer, data.flatten()])

            # Process when we have enough audio
            if len(buffer) >= chunk_samples:
                chunk = buffer[:chunk_samples]
                buffer = buffer[chunk_samples:]

                # Check if audio has content (not silence)
                if np.abs(chunk).max() > 0.01:
                    text = self.transcribe_chunk(chunk)
                    if text and text not in ["", " ", "."]:
                        self.transcriptions.append(text)
                        # Print transcription in real-time
                        print(f"\r\033[K  >> {text}", flush=True)
                        print()

        except queue.Empty:
            continue
        except Exception as e:
            print(f"\nError: {e}")

    # Process remaining buffer
    if len(buffer) > self.sample_rate * 0.5:  # At least 0.5s
        if np.abs(buffer).max() > 0.01:
            text = self.transcribe_chunk(buffer)
            if text and text not in ["", " ", "."]:
                self.transcriptions.append(text)
                print(f"\r\033[K  >> {text}", flush=True)
                print()

examples.mic_realtime.RealtimeTranscriber.run

run()

Start real-time transcription.

Source code in examples/mic_realtime.py
def run(self):
    """Start real-time transcription."""
    print()
    print("=" * 60)
    print(" Real-Time Transcription")
    print(f" Chunk size: {self.chunk_duration}s")
    print("=" * 60)
    print()
    print("Speak now! Press Ctrl+C to stop.")
    print()
    print("-" * 60)

    self.is_recording = True

    # Start audio stream
    stream = sd.InputStream(
        samplerate=self.sample_rate,
        channels=CHANNELS,
        dtype=np.float32,
        callback=self.audio_callback,
        blocksize=int(self.sample_rate * 0.1)  # 100ms blocks
    )

    # Start processing thread
    process_thread = threading.Thread(target=self.process_audio, daemon=True)
    process_thread.start()

    try:
        with stream:
            while True:
                time.sleep(0.1)
    except KeyboardInterrupt:
        print("\n")
        print("-" * 60)
        self.is_recording = False

        # Wait for processing to finish
        print("Processing remaining audio...")
        process_thread.join(timeout=5)

    return self.transcriptions

examples.mic_realtime.main

main()
Source code in examples/mic_realtime.py
def main():
    parser = argparse.ArgumentParser(
        description="Real-Time Microphone Transcription",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
    python examples/mic_realtime.py                   # 3 second chunks
    python examples/mic_realtime.py --chunk 2         # 2 second chunks (faster)
    python examples/mic_realtime.py --model parakeet  # Fast English model
    python examples/mic_realtime.py --language en     # Force English
        """
    )
    parser.add_argument("--model", "-m", default="whisper-small",
                        help="Model to use (default: whisper-small)")
    parser.add_argument("--chunk", "-c", type=float, default=3.0,
                        help="Chunk duration in seconds (default: 3.0)")
    parser.add_argument("--language", "-l", help="Language code (e.g., en, es)")
    parser.add_argument("--list-models", action="store_true", help="List available models")
    args = parser.parse_args()

    print()
    print("=" * 60)
    print(" Real-Time Microphone Transcription - vllm-mlx")
    print("=" * 60)
    print()

    if args.list_models:
        print("Available models:")
        for alias, full_name in MODEL_ALIASES.items():
            rec = " (recommended for real-time)" if alias == "whisper-small" else ""
            print(f"  {alias:20} -> {full_name}{rec}")
        return

    # Resolve model alias
    model_name = MODEL_ALIASES.get(args.model, args.model)

    # Create transcriber
    transcriber = RealtimeTranscriber(
        model_name=model_name,
        chunk_duration=args.chunk,
        language=args.language
    )

    # Load model
    transcriber.load_model()

    # Run transcription
    transcriptions = transcriber.run()

    # Show summary
    print()
    print("=" * 60)
    print(" FULL TRANSCRIPT")
    print("=" * 60)
    print()
    full_text = " ".join(transcriptions)
    print(full_text if full_text else "(No speech detected)")
    print()
    print("=" * 60)

Complete contract reference

Expand any definition for its exact inputs, annotations, defaults, return contract, directly raised exceptions, source-grounded behavior, and immutable line link. This section includes private and nested definitions that ordinary API generators omit.

examples.mic_realtime.RealtimeTranscriber · class
examples.mic_realtime.RealtimeTranscriber(model_name: str, chunk_duration: float = 3.0, language: str = None)

Real-time audio transcription using Whisper.

Parameters

Name Type Required Default Description
model_name str yes none Required positional or keyword input.
chunk_duration float no 3.0 Optional positional or keyword input; defaults to 3.0.
language str no None Optional positional or keyword input; defaults to None.

Returns

  • Constructs: examples.mic_realtime.RealtimeTranscriber

Exceptions and behavior

Class RealtimeTranscriber declares 6 direct member(s). No direct raise statement appears in this definition.

View source #L45-L171.

examples.mic_realtime.RealtimeTranscriber.__init__ · method
examples.mic_realtime.RealtimeTranscriber.__init__(model_name: str, chunk_duration: float = 3.0, language: str = None) -> not annotated

Method RealtimeTranscriber.__init__ updates self.model_name, self.chunk_duration, self.language, self.sample_rate; calls queue.Queue.

Parameters

Name Type Required Default Description
model_name str yes none Required positional or keyword input.
chunk_duration float no 3.0 Optional positional or keyword input; defaults to 3.0.
language str no None Optional positional or keyword input; defaults to None.

Returns

  • Type: not annotated

Exceptions and behavior

Method RealtimeTranscriber.__init__ updates self.model_name, self.chunk_duration, self.language, self.sample_rate; calls queue.Queue. No direct raise statement appears in this definition.

View source #L48-L60.

examples.mic_realtime.RealtimeTranscriber.load_model · method
examples.mic_realtime.RealtimeTranscriber.load_model() -> not annotated

Load the STT model.

Parameters

This callable has no explicit inputs.

Returns

  • Type: not annotated

Exceptions and behavior

Method RealtimeTranscriber.load_model updates self.engine; calls print, STTEngine, self.engine.load. No direct raise statement appears in this definition.

View source #L62-L68.

examples.mic_realtime.RealtimeTranscriber.audio_callback · method
examples.mic_realtime.RealtimeTranscriber.audio_callback(indata, frames, time_info, status) -> not annotated

Callback for audio input stream.

Parameters

Name Type Required Default Description
indata not annotated yes none Required positional or keyword input.
frames not annotated yes none Required positional or keyword input.
time_info not annotated yes none Required positional or keyword input.
status not annotated yes none Required positional or keyword input.

Returns

  • Type: not annotated

Exceptions and behavior

Method RealtimeTranscriber.audio_callback calls print, self.audio_queue.put, indata.copy. No direct raise statement appears in this definition.

View source #L70-L75.

examples.mic_realtime.RealtimeTranscriber.transcribe_chunk · method
examples.mic_realtime.RealtimeTranscriber.transcribe_chunk(audio_data) -> not annotated

Transcribe a chunk of audio.

Parameters

Name Type Required Default Description
audio_data not annotated yes none Required positional or keyword input.

Returns

  • Type: not annotated
  • Direct return expressions: result.text.strip()

Exceptions and behavior

Method RealtimeTranscriber.transcribe_chunk calls tempfile.NamedTemporaryFile, sf.write, self.engine.transcribe, result.text.strip; returns result.text.strip(). No direct raise statement appears in this definition.

View source #L77-L90.

examples.mic_realtime.RealtimeTranscriber.process_audio · method
examples.mic_realtime.RealtimeTranscriber.process_audio() -> not annotated

Process audio chunks in real-time.

Parameters

This callable has no explicit inputs.

Returns

  • Type: not annotated

Exceptions and behavior

Method RealtimeTranscriber.process_audio calls int, np.array, self.audio_queue.empty, self.audio_queue.get. No direct raise statement appears in this definition.

View source #L92-L129.

examples.mic_realtime.RealtimeTranscriber.run · method
examples.mic_realtime.RealtimeTranscriber.run() -> not annotated

Start real-time transcription.

Parameters

This callable has no explicit inputs.

Returns

  • Type: not annotated
  • Direct return expressions: self.transcriptions

Exceptions and behavior

Method RealtimeTranscriber.run updates self.is_recording; calls print, sd.InputStream, int, threading.Thread; returns self.transcriptions. No direct raise statement appears in this definition.

View source #L131-L171.

examples.mic_realtime.main · function
examples.mic_realtime.main() -> not annotated

Function main calls argparse.ArgumentParser, parser.add_argument, parser.parse_args, print; returns None.

Parameters

This callable has no explicit inputs.

Returns

  • Type: not annotated
  • Direct return expressions: None

Exceptions and behavior

Function main calls argparse.ArgumentParser, parser.add_argument, parser.parse_args, print; returns None. No direct raise statement appears in this definition.

View source #L174-L232.

Complete symbol map

This map also includes private definitions and nested helpers. The signature column exposes every explicit input even when an internal helper has no dedicated parameter prose.

Symbol Kind Signature and inputs What it does Source
RealtimeTranscriber class RealtimeTranscriber(model_name: str, chunk_duration: float = 3.0, language: str = None) Real-time audio transcription using Whisper. #L45-L171
RealtimeTranscriber.__init__ method RealtimeTranscriber.__init__(model_name: str, chunk_duration: float = 3.0, language: str = None) -> not annotated Method RealtimeTranscriber.__init__ updates self.model_name, self.chunk_duration, self.language, self.sample_rate; calls queue.Queue. #L48-L60
RealtimeTranscriber.load_model method RealtimeTranscriber.load_model() -> not annotated Load the STT model. #L62-L68
RealtimeTranscriber.audio_callback method RealtimeTranscriber.audio_callback(indata, frames, time_info, status) -> not annotated Callback for audio input stream. #L70-L75
RealtimeTranscriber.transcribe_chunk method RealtimeTranscriber.transcribe_chunk(audio_data) -> not annotated Transcribe a chunk of audio. #L77-L90
RealtimeTranscriber.process_audio method RealtimeTranscriber.process_audio() -> not annotated Process audio chunks in real-time. #L92-L129
RealtimeTranscriber.run method RealtimeTranscriber.run() -> not annotated Start real-time transcription. #L131-L171
main function main() -> not annotated Function main calls argparse.ArgumentParser, parser.add_argument, parser.parse_args, print; returns None. #L174-L232