Skip to main content

Moonshine Voice Python Package

A fast, accurate, on-device AI library for building interactive voice applications. Join our Discord to get help and support.

Installation

pip install moonshine-voice

Training a domain adapter is an opt-in extra (pip install 'moonshine-voice[finetune]', also available as [lora]) so the inference install does not pull in PyTorch or Transformers. See Domain Customization.

Quick Start

# Listens to the microphone, logging to the console when there are 
# speech updates.
moonshine-voice mic

Installing the package adds a moonshine-voice command (with a shorter moonshine alias) that groups the built-in tools as subcommands: mic, transcribe, tts, agent, download, g2p, and lora. Run moonshine-voice --help, or moonshine-voice <command> --help for a specific tool. Each subcommand is equivalent to python -m moonshine_voice.<module>, so either invocation style works. The lora subcommand needs the extra above.

Example

"""Transcribes live audio from the default microphone"""
import time
from moonshine_voice import MicTranscriber

# MicTranscriber handles connecting to the microphone, capturing the audio
# data, detecting voice activity, breaking the speech up into segments,
# transcribing it, and calling you back as the results firm up over time.
mic = (
    MicTranscriber()
    .on_text(lambda text: print(f"\r{text}", end="", flush=True))
    .on_line(lambda line: print(f"\r{line.text}"))
)

# Downloads the model files and caches them, so the first call is the slow one.
mic.load()
mic.start()
print("Listening to the microphone, press Ctrl+C to stop...")

while True:
    time.sleep(0.1)

on_text gives you the line as it is being spoken, rewritten as the model changes its mind, and on_line gives you each line once it is final. Configuration is chainable and everything has a working default: language(), model_arch(), device(), update_interval(), and on_progress() for a download bar.

When you need more than the text, such as line ids, speaker spans, or word timings, attach a listener object instead. Both styles can be used together.

from moonshine_voice import MicTranscriber, TranscriptEventListener

class TestListener(TranscriptEventListener):
    def on_line_started(self, event):
        print(f"Line started: {event.line.text}")

    def on_line_text_changed(self, event):
        print(f"Line text changed: {event.line.text}")

    def on_line_completed(self, event):
        print(f"Line completed: {event.line.text}")

mic = MicTranscriber()
mic.add_listener(TestListener())
mic.load()
mic.start()

Other Sources

If you have a different source you're capturing audio from you can supply it directly to a transcriber.

"""Transcribes live audio from an arbitrary audio source."""
from moonshine_voice import (
    Transcriber,
    TranscriptEventListener,
    get_model_for_language,
    load_wav_file,
    get_assets_path,
)
import os
from typing import Iterator, Tuple


def audio_chunk_generator(
    wav_file_path: str, chunk_duration: float = 0.1
) -> Iterator[Tuple[list, int]]:
    """
    Example function that loads a WAV file and yields audio chunks.

    This demonstrates how you can integrate your own proprietary
    audio data capture sources. Replace this function with your own
    implementation that yields (audio_chunk, sample_rate) tuples.

    Args:
        wav_file_path: Path to the WAV file to load
        chunk_duration: Duration of each chunk in seconds

    Yields:
        Tuple of (audio_chunk, sample_rate) where:
        - audio_chunk: List of float audio samples
        - sample_rate: Sample rate in Hz
    """
    audio_data, sample_rate = load_wav_file(wav_file_path)
    chunk_size = int(chunk_duration * sample_rate)

    for i in range(0, len(audio_data), chunk_size):
        chunk = audio_data[i: i + chunk_size]
        yield (chunk, sample_rate)


model_path, model_arch = get_model_for_language("en")

transcriber = Transcriber(
    model_path=model_path, model_arch=model_arch)

stream = transcriber.create_stream(update_interval=0.5)
stream.start()


class TestListener(TranscriptEventListener):
    def on_line_started(self, event):
        print(f"{event.line.start_time:.2f}s: Line started: {event.line.text}")

    def on_line_text_changed(self, event):
        print(
            f"{event.line.start_time:.2f}s: Line text changed: {event.line.text}")

    def on_line_completed(self, event):
        print(f"{event.line.start_time:.2f}s: Line completed: {event.line.text}")


listener = TestListener()
stream.add_listener(listener)

# Feed audio chunks from the generator into the stream.
wav_file_path = os.path.join(get_assets_path(), "two_cities.wav")
for chunk, sample_rate in audio_chunk_generator(wav_file_path):
    stream.add_audio(chunk, sample_rate)

stream.stop()
stream.close()

Voice Commands

Voice commands go through AgentFlow. Register the phrases you want to listen for and it handles the rest: it downloads the speech recognition, speech synthesis and phrase-matching models, opens the microphone, matches what the user said semantically rather than by exact wording, and runs your handler.

from moonshine_voice import AgentFlow

def lights_on(d):
    print("\n💡 LIGHTS ON!")

def lights_off(d):
    print("\n🌑 LIGHTS OFF!")

runner = (
    AgentFlow()
    .always("turn on the lights", lights_on)
    .always("turn off the lights", lights_off)
)

load() downloads and opens everything it needs, and start_listening() opens the microphone. There's nothing else to construct:

runner.load()
runner.start_listening()
try:
    while True:
        time.sleep(0.1)
except KeyboardInterrupt:
    print("\n\nStopping...", file=sys.stderr)
finally:
    runner.close()

Configuration is chainable, and everything has a working default — language(), voice(), trigger_threshold(), on_heard() / on_said() / on_error() for observing the conversation, and use_mic_transcriber() / use_text_to_speech() when you'd rather supply your own. To drive a runner from text instead of audio, turn the microphone off with microphone(False) and feed it handle_utterance().

For multi-turn conversations — asking a question, confirming an answer, spelling out a password — register a flow with listen_for() instead of a global. See examples/python/agent_flow.py, or run moonshine-voice agent.

Speaking

TextToSpeech follows the same shape: configure it, load() it, then use it.

from moonshine_voice import TextToSpeech

tts = TextToSpeech().language("en_us").voice("kokoro_af_heart")
tts.load()
tts.say("Hello from Moonshine.")
tts.wait()

say() returns immediately and queues the utterance, pre-synthesizing the next one while the current one plays, so consecutive calls run together without a gap. wait() blocks until the queue drains, stop() cancels it, and is_talking() polls. If you would rather have the samples than hear them, use synthesize(). The chainable setters are language(), voice(), output_device(), volume(), models_from(), and on_progress() for a download bar.

To speak in someone else's voice, clone_from() takes a few seconds of them talking, either as a .wav file or as a (pcm, sample_rate) pair.

tts = TextToSpeech().language("en_us").cloning()
tts.load()
tts.clone_from("some-speech.wav")
tts.say("Now I sound like you.")

cloning() fetches ZipVoice and clone ASR during load() so clone_from() only swaps the reference clip. Call it before load(); without it, clone_from() / start_cloning() raise. To capture the reference clip from the microphone instead, start_cloning() hands back a VoiceClone that listens until it has heard enough usable speech.

clone = tts.start_cloning()
clone.on_ready(lambda: print("Got it, you can stop talking."))
clone.from_microphone()
tts.clone_from(clone)

Multiple Languages

The framework currently supports English, Spanish, German, Mandarin, Japanese, Korean, Vietnamese, Tagalog, Ukrainian, and Arabic for speech to text. We are working on wider language support, and you can see which are supported in your version by calling supported_languages(). To use a language, request it using get_model_for_language() passing in the two-letter language code. For example get_model_for_language("es") will download the Spanish models and pass the information you need to create Transcriber objects using them.

Documentation

For more information, see the main Moonshine Voice documentation.

License

The code and the models are released under the MIT License by default, in every language and at every size - see the main project repository for details. The only exceptions are the legacy non-streaming models for languages other than English, which stay under the non-commercial Moonshine Community License; that list is enumerated in the project LICENSE.

Metadata

Release files for moonshine-voice 0.1.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for moonshine-voice 0.1.6
File Actions
moonshine_voice-0.1.6-py3-none-win_amd64.whl Python 3 none Windows x86-64 Details for moonshine_voice-0.1.6-py3-none-win_amd64.whl
moonshine_voice-0.1.6-py3-none-manylinux_2_34_x86_64.whl Python 3 none Linux glibc 2.34+ x86-64 Details for moonshine_voice-0.1.6-py3-none-manylinux_2_34_x86_64.whl
moonshine_voice-0.1.6-py3-none-manylinux_2_34_aarch64.whl Python 3 none Linux glibc 2.34+ ARM64 Details for moonshine_voice-0.1.6-py3-none-manylinux_2_34_aarch64.whl
moonshine_voice-0.1.6-py3-none-manylinux_2_31_aarch64.whl Python 3 none Linux glibc 2.31+ ARM64 Details for moonshine_voice-0.1.6-py3-none-manylinux_2_31_aarch64.whl
moonshine_voice-0.1.6-py3-none-macosx_15_0_arm64.whl Python 3 none macOS 15.0+ ARM64 Details for moonshine_voice-0.1.6-py3-none-macosx_15_0_arm64.whl

Total release size: 92.7 MB

Release files / moonshine_voice-0.1.6-py3-none-win_amd64.whl

Download URL moonshine_voice-0.1.6-py3-none-win_amd64.whl
Size 16.6 MB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
29a54f9249d41735db62b1f97272905cf114554f293c166f0f4f81655a4a2cfc
BLAKE2b-256 checksum
How to use checksums
7f07aafde753e2819bc5dca333b45a90f3dad475a41da2c97ddd60ccc6e37479
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Release files / moonshine_voice-0.1.6-py3-none-manylinux_2_34_x86_64.whl

Download URL moonshine_voice-0.1.6-py3-none-manylinux_2_34_x86_64.whl
Size 20.0 MB
Tags Linux glibc 2.34+ x86-64 Python 3
SHA-256 checksum
How to use checksums
04e438f393af3f963ac7988204f379d04a9c8949801595cab4bd68a7ceedf6c7
BLAKE2b-256 checksum
How to use checksums
544720993e0676642cf05273b6b2fed13076a5b4028156c938dd86136bb71797
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.16

Release files / moonshine_voice-0.1.6-py3-none-manylinux_2_34_aarch64.whl

Download URL moonshine_voice-0.1.6-py3-none-manylinux_2_34_aarch64.whl
Size 18.7 MB
Tags Linux glibc 2.34+ ARM64 Python 3
SHA-256 checksum
How to use checksums
41bfd82ca61f1878e4681c25cf1a6c8f2692a14c2ca88a6840ffa00c452891fe
BLAKE2b-256 checksum
How to use checksums
8388c2088ad66599aa81db816a4c0f1d25d00d40d1d9781c76a132990a86bedd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.16

Release files / moonshine_voice-0.1.6-py3-none-manylinux_2_31_aarch64.whl

Download URL moonshine_voice-0.1.6-py3-none-manylinux_2_31_aarch64.whl
Size 18.6 MB
Tags Linux glibc 2.31+ ARM64 Python 3
SHA-256 checksum
How to use checksums
16589b0e86e4a66fbbb7bb1429deaa56a47f33fdc1cd0aef4b781ccbf49c95df
BLAKE2b-256 checksum
How to use checksums
3fadf6cad5893e822303fed6c0931127274e7bfc19ebdad5aaa7af87888d242b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.11

Release files / moonshine_voice-0.1.6-py3-none-macosx_15_0_arm64.whl

Download URL moonshine_voice-0.1.6-py3-none-macosx_15_0_arm64.whl
Size 18.7 MB
Tags Python 3 macOS 15.0+ ARM64
SHA-256 checksum
How to use checksums
71f0fa9d0b01fa317f86a85e846e9faa247be985f92b50970817dd999e400ff4
BLAKE2b-256 checksum
How to use checksums
25ad91ef5908f592faff47dd4e03073b3eb073ce88f984f6bc86031e02057a69
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.13

Security for moonshine-voice 0.1.6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.6 This release

5 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page