This article has you record about seven seconds of your own voice and use it to make your Mac read any text file aloud in that voice. make speak TEXT=text/note.txt writes out/note.wav, generated on the Mac by Alibaba’s Qwen3-TTS, an open-weight model (its weights are free to download and run). There is no hosted API, and once the models are downloaded every make target except download runs with Hugging Face’s offline mode on, so nothing is fetched. A second command, make check, checks the result in numbers you can read instead of judging by ear. Whisper, OpenAI’s open speech-recognition model, transcribes the clip for comparison with your text, and the clip’s voice is scored against your recording and against the same model reading with no reference.

Text-to-speech (TTS) turns text into audio. Voice cloning is TTS that copies a particular speaker from a short sample of them, called the reference clip. Qwen3-TTS does it in context: you hand it the reference audio together with a transcript of what the audio says, and it carries on speaking your new text in the same voice, with no training step. That is why both halves matter, and why much of this article is about getting a clean clip with an exact transcript.

Clone your own voice, or a voice whose owner has said yes. A voice is personal data, and a convincing clone of someone who has not agreed is how impersonation scams work. The reference clip used here is the author’s own recording, made for this article. The code keeps every recording and every generated file out of git, and this page publishes no audio.

If you would rather use a hosted service, How Higgsfield Does Audio and Voice covers cloning through one. This article runs everything on your Mac.

Prerequisites

  • A Mac with Apple silicon and 16 GB of memory or more. The model runs on MLX, Apple’s array framework for the GPU in M-series chips, so Intel Macs are out. Written and validated on an M5 Max with 128 GB running macOS 27.2.1, called “the review machine” below. MLX reported a peak of 6.1 to 7.3 GB of memory allocated per run.
  • uv 0.13 or newer (brew install uv). Validated with uv 0.13.6, which installs Python 3.12 for the project on its own.
  • ffmpeg 9 or newer (brew install ffmpeg), used to record from the microphone. Validated with ffmpeg 9.0.2.
  • About 4 GB of free disk for the two models: 2.0 GB for the Qwen3-TTS checkpoint (a published set of model weights), including its 0.7 GB speech tokenizer, and 1.6 GB for Whisper.
  • A microphone and a quiet room. The built-in MacBook microphone is enough.
  • Familiarity with the Hugging Face Hub, where both models are downloaded from. No account or token is needed.

Both models are permissively licensed. The Qwen3-TTS checkpoints are Apache-2.0, and OpenAI publishes Whisper large-v3-turbo under MIT. Neither model card adds restrictions on top of that, so the limits on cloning are the legal and ethical ones above, not the license.

Step 1: Create the project and keep your voice out of git

The project will hold a recording of your voice and every clip generated from it, and a clone is only as private as those files. So the .gitignore comes first, before any audio exists, and it ignores audio by extension as well as by folder. That way a .wav saved somewhere unexpected is ignored too.

Create the file

mkdir -p ~/projects/voiceclone
cd ~/projects/voiceclone
touch .gitignore

Add the code: .gitignore

# Python and uv
.venv/
__pycache__/
*.pyc
.pytest_cache/

# Your voice and everything made from it: biometric-adjacent, never commit
voice/
out/
*.wav
*.mp3
*.aiff
*.m4a

# macOS
.DS_Store

Detailed breakdown

  • voice/ will hold reference.wav (your recording) and reference.txt (its transcript). out/ will hold the generated speech. Both are ignored whole.
  • The extension rules (*.wav and the rest) are a second line of defense: a clip written to the project root or to text/ is still ignored.
  • The first block is the usual Python set for a project managed by uv.

With the ignore rules in place, scaffold a packaged Python project:

uv init --package --name voiceclone --python 3.12 --no-readme --author-from none .

--package creates a src/voiceclone/ layout with a build backend. That matters in Step 6, because it is what puts the voiceclone command on the path inside the virtualenv. --python 3.12 pins the interpreter in .python-version. The pin is the interpreter this project was validated on, not a hard minimum. --no-readme and --author-from none leave out a README.md and an authors entry copied from your git configuration, neither of which this project uses. uv init keeps the .gitignore you just wrote.

Step 2: Add the dependencies and name the models

One library does almost all the work. mlx-audio runs speech models on MLX, and it includes both Qwen3-TTS for generating speech and Whisper for transcribing it, so the project needs no PyTorch and no second audio stack. It is pinned to an exact version because it is new and changes often between releases: version 0.6.7 is the one this article was validated against, and its loader is what the code in Steps 5 to 9 calls.

Before adding anything, add a release-age gate. It tells uv to refuse any package version published in the last three days. A compromised release is usually caught and pulled within hours, so a three-day wait keeps you clear of most of them while they are live. It has to be in pyproject.toml before uv add runs, because the gate applies when uv resolves versions.

printf '\n[tool.uv]\nexclude-newer = "3 days"\n' >> pyproject.toml
uv add "mlx-audio==0.6.7"
uv add --dev pytest

Create the file

uv init created pyproject.toml; edit it so it matches the listing below.

open -e pyproject.toml

Add the code: pyproject.toml

[project]
name = "voiceclone"
version = "0.1.0"
description = "Clone your own voice locally with Qwen3-TTS on Apple silicon"
requires-python = ">=3.12"
dependencies = [
    "mlx-audio==0.6.7",
]

[project.scripts]
voiceclone = "voiceclone:main"

[build-system]
requires = ["uv_build>=0.13.6,<0.14.0"]
build-backend = "uv_build"

[tool.uv]
exclude-newer = "3 days"

[dependency-groups]
dev = [
    "pytest>=9.2.0",
]

Detailed breakdown

  • dependencies holds the single runtime dependency, pinned with ==. It pulls in MLX itself, NumPy, Hugging Face’s transformers (for the tokenizers) and the hf download tool used in Step 3.
  • [project.scripts] was written by uv init --package. It maps the voiceclone command to the main function you write in Step 6.
  • The uv_build range under [build-system] follows your uv version, so yours may name a different one. Leave whatever uv init wrote. The same goes for the pytest floor, which is whatever was current when you ran uv add.
  • The only hand edit is the description line, which uv init fills with a placeholder.

The project uses two checkpoints, and two modules need their names. Put them in one place.

Create the file

touch src/voiceclone/models.py

Add the code: src/voiceclone/models.py

"""The two checkpoints this project runs. Keep these in step with the Makefile."""

# Qwen3-TTS comes in Base, CustomVoice and VoiceDesign variants; only Base
# clones a voice from a reference clip. This is the smallest Base checkpoint,
# quantized to 8 bits for MLX.
TTS_MODEL = "mlx-community/Qwen3-TTS-12Hz-0.6B-Base-8bit"

# Whisper large-v3-turbo, converted for MLX, used to hear what a clip says.
WHISPER_MODEL = "mlx-community/whisper-large-v3-turbo-asr-fp16"

Detailed breakdown

  • Why Base. Qwen3-TTS ships three variants. CustomVoice speaks in one of a fixed set of named voices, and VoiceDesign builds a voice from a written description. Only the Base variant takes a reference clip, so it is the only one that clones. Point the code at a CustomVoice checkpoint and generation stops with CustomVoice model requires 'voice' (speaker name), because that variant has no way to take your clip.
  • Why 0.6B at 8 bits. Qwen3-TTS comes in 0.6-billion and 1.7-billion parameter sizes. The mlx-community organization on Hugging Face publishes MLX conversions of both, at several precisions. An 8-bit conversion is quantized: most weights are stored in 8 bits instead of 16, typically at a small cost in accuracy. Some parts, including the speech tokenizer, stay at 16 bits, so the 8-bit 0.6B repository is 2.0 GB against 2.5 GB for the 16-bit one. Generation is sampled, so every unseeded run of the same text gives a slightly different take (Step 8 shows this). On the review machine, one take from each size scored 0.984 for 1.7B and 0.989 for 0.6B on Step 9’s speaker similarity (1.0 means identical voices), a difference no larger than the spread between takes. The 1.7B take was slower, and a listening test did not favor it, so this article uses the smaller size. You can swap in mlx-community/Qwen3-TTS-12Hz-1.7B-Base-8bit with --model later without changing any code.
  • 12Hz in the name is the rate of the model’s audio codes. Its speech tokenizer describes one second of speech as 12.5 frames of discrete codes (24,000 audio samples, or amplitude readings, per second, divided into 1,920-sample frames), and a decoder turns them back into a 24 kHz waveform. The 24 kHz figure is why the recording in Step 7 is made at that rate.
  • The Whisper repository chosen here includes the tokenizer files the transcriber needs. The similarly named mlx-community/whisper-large-v3-turbo does not, and fails with Processor not found.

Step 3: Add a Makefile and download the models

Every command in the rest of the article runs through make, so the Makefile comes before the code it calls. Some of its targets (record, speak, check) will not work until the steps that build what they run. Writing the file once now, in full, means you never edit it again, and plain make prints a map of where the article is going.

Create the file

touch Makefile

Add the code: Makefile

.DEFAULT_GOAL := help

MIC  ?= default
TEXT ?= text/hello.txt
OUT  ?= out/$(basename $(notdir $(TEXT))).wav

# Same checkpoints as src/voiceclone/models.py.
TTS_MODEL     := mlx-community/Qwen3-TTS-12Hz-0.6B-Base-8bit
WHISPER_MODEL := mlx-community/whisper-large-v3-turbo-asr-fp16

# Never contact the Hugging Face Hub, except in `download`.
export HF_HUB_OFFLINE := 1
# Quieter model loading: no download bars, no transformers warnings.
export HF_HUB_DISABLE_PROGRESS_BARS := 1
export TRANSFORMERS_VERBOSITY := error

.PHONY: help install download mics record speak check test clean

help: ## Show this help
	@awk 'BEGIN {FS = ":.*## "} /^[a-z-]+:.*## / {printf "  %-9s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
	@echo
	@echo "  Variables: MIC=$(MIC) TEXT=$(TEXT) OUT=$(OUT)"

install: ## Create the virtualenv and install dependencies
	uv sync

download: ## Fetch both models into the Hugging Face cache
	HF_HUB_OFFLINE=0 uv run hf download $(TTS_MODEL) --quiet
	HF_HUB_OFFLINE=0 uv run hf download $(WHISPER_MODEL) --quiet

mics: ## List microphones ffmpeg can record from
	@ffmpeg -hide_banner -f avfoundation -list_devices true -i "" 2>&1 \
		| sed -n '/audio devices/,$$p' | grep -E '^\[AVF' | sed 's/^\[[^]]*\] //'

record: ## Record voice/reference.wav (15 s, read script.txt aloud)
	@mkdir -p voice
	@cp script.txt voice/reference.txt
	@echo "Read this aloud after the Speak now prompt:"
	@echo
	@sed 's/^/    /' script.txt
	@echo
	@ffmpeg -hide_banner -loglevel error -y -f avfoundation -t 15 -i ":$(MIC)" \
		-ac 1 -ar 24000 -c:a pcm_s16le voice/raw.wav & \
		sleep 1.5; echo ">>> Speak now. Recording stops by itself after 15 seconds."; wait
	@ffmpeg -hide_banner -loglevel error -y -i voice/raw.wav \
		-af "silenceremove=start_periods=1:start_threshold=-45dB,areverse,silenceremove=start_periods=1:start_threshold=-45dB,areverse" \
		-c:a pcm_s16le voice/reference.wav
	@rm voice/raw.wav
	@uv run voiceclone reference --transcribe

speak: ## Read TEXT aloud in your voice, writing OUT
	uv run voiceclone speak $(TEXT) $(OUT)

check: ## Verify OUT says TEXT, in your voice
	uv run voiceclone check $(OUT) $(TEXT)

test: ## Run the unit tests
	uv run pytest -v

clean: ## Delete generated audio (keeps your reference clip)
	rm -rf out

Detailed breakdown

  • help is the default. .DEFAULT_GOAL := help makes plain make print the target list. The awk line builds it from the ## comment after each target, so the help text cannot drift from the targets.
  • TEXT and OUT are the input and output of a clone. OUT is derived from TEXT, so make speak TEXT=text/note.txt writes out/note.wav without naming the output.
  • TTS_MODEL and WHISPER_MODEL repeat the names in models.py for the download target. Change both places if you swap a checkpoint.
  • export HF_HUB_OFFLINE := 1 keeps every target off the network. Without it, each model load asks the Hugging Face Hub whether the cached copy is current, even though nothing needs downloading. download overrides it with HF_HUB_OFFLINE=0 on its own lines, so it is the one target that goes online.
  • The other two export lines quiet the libraries for every target. They turn off Hugging Face’s download progress bars and the transformers warnings printed while a model loads, which otherwise bury the measurements this project prints.
  • install runs uv sync, which creates the project’s virtual environment (the “virtualenv” in the help text) in .venv/. uv run does the same on demand, so you rarely need it by hand.
  • record is explained in Step 7, where you run it. In short, it captures 15 seconds from the microphone, trims the silence at each end, and then checks the result.
  • speak and check call the voiceclone command you build in Steps 6 to 9.
  • Recipe lines must start with a tab, not spaces. If you copy the listing and make reports missing separator, that is the cause.

Run plain make to confirm the help screen:

make
  help      Show this help
  install   Create the virtualenv and install dependencies
  download  Fetch both models into the Hugging Face cache
  mics      List microphones ffmpeg can record from
  record    Record voice/reference.wav (15 s, read script.txt aloud)
  speak     Read TEXT aloud in your voice, writing OUT
  check     Verify OUT says TEXT, in your voice
  test      Run the unit tests
  clean     Delete generated audio (keeps your reference clip)

  Variables: MIC=default TEXT=text/hello.txt OUT=out/hello.wav

Then fetch both models, about 3.6 GB in all:

make download

The models land in the Hugging Face cache under ~/.cache/huggingface/hub/, and the command prints each model’s folder there when it finishes. Downloading them now, rather than at first use, separates the one step that needs the network from everything after it. Every other target runs offline from here on, and Step 10 shows what that guarantees. The hf tool may print a warning that you are sending unauthenticated requests. It is harmless here, because both repositories are public.

Step 4: Validate a reference clip

Most problems with a reference clip raise no error. The model returns audio whatever you give it, so a bad clip shows up only as a worse clone. This step writes the guard that runs before any generation and turns the problems it can detect into an error you can read. It needs no model, so it is also the first piece you can test.

Create the file

touch src/voiceclone/reference.py

Add the code: src/voiceclone/reference.py

"""Load and sanity-check the reference clip the voice is cloned from."""

import wave
from dataclasses import dataclass
from pathlib import Path

# Qwen3-TTS works at 24 kHz, and its speaker encoder assumes that rate without
# checking, so the recording step captures at this rate directly.
SAMPLE_RATE = 24_000
MIN_SECONDS = 3.0
MAX_SECONDS = 20.0


@dataclass(frozen=True)
class WavInfo:
    path: Path
    sample_rate: int
    channels: int
    seconds: float


@dataclass(frozen=True)
class Reference:
    audio: WavInfo
    transcript: str


def wav_info(path: Path) -> WavInfo:
    """Read a PCM WAV header with the standard library."""
    with wave.open(str(path), "rb") as w:
        rate = w.getframerate()
        return WavInfo(
            path=path,
            sample_rate=rate,
            channels=w.getnchannels(),
            seconds=w.getnframes() / rate,
        )


def load_reference(voice_dir: Path) -> Reference:
    """Return the reference clip and its transcript, or explain what is wrong."""
    wav_path = voice_dir / "reference.wav"
    txt_path = voice_dir / "reference.txt"
    if not wav_path.exists():
        raise ValueError(f"{wav_path} not found; run `make record` first")
    if not txt_path.exists():
        raise ValueError(f"{txt_path} not found; it holds what the clip says")

    info = wav_info(wav_path)
    transcript = " ".join(txt_path.read_text().split())
    problems = []
    if info.sample_rate != SAMPLE_RATE:
        problems.append(f"sample rate is {info.sample_rate} Hz, need {SAMPLE_RATE}")
    if info.channels != 1:
        problems.append(f"{info.channels} channels, need mono")
    if not MIN_SECONDS <= info.seconds <= MAX_SECONDS:
        problems.append(
            f"clip is {info.seconds:.1f} s, keep it between "
            f"{MIN_SECONDS:.0f} and {MAX_SECONDS:.0f} s"
        )
    if not transcript:
        problems.append(f"{txt_path} is empty")
    if problems:
        raise ValueError("reference clip rejected: " + "; ".join(problems))
    return Reference(audio=info, transcript=transcript)

Detailed breakdown

  • WavInfo is read with Python’s standard wave module, which parses the header of an uncompressed PCM WAV file. Step 7 records in exactly that format, so no audio library is needed to measure a clip.
  • load_reference expects a folder holding reference.wav and reference.txt. Keeping the transcript in a file beside the clip means the two travel together, and Step 7 writes both at once.
  • The transcript is normalized with " ".join(...split()), which joins wrapped lines and squeezes runs of spaces. The model gets one clean line.
  • The checks are gathered, not raised one at a time, so a clip that is both stereo and too short reports both problems in one run.
  • The duration bounds are this project’s choice. The Qwen3-TTS model card says a clip of about 3 seconds is enough, so 3 is the floor. The 20-second ceiling exists because the whole reference is fed to the model ahead of every paragraph it speaks (Step 8 explains why). A long clip slows every call, and the library’s own source notes that long reference audio makes its output more likely to degrade.
  • 24 kHz is required by the speaker measurement in Step 9. Generation resamples other rates when it loads the clip, but Step 9 hands the raw samples to mlx-audio’s speaker encoder (the part of the model that summarizes a voice, described in Step 8), which assumes 24 kHz without checking. A 44.1 kHz clip would be measured as if it were slowed down, with no error. Rejecting it here prevents that.

Create the file

mkdir -p tests
touch tests/test_reference.py

Add the code: tests/test_reference.py

import wave

import pytest

from voiceclone.reference import load_reference


def write_wav(path, seconds, rate=24_000, channels=1):
    with wave.open(str(path), "wb") as w:
        w.setnchannels(channels)
        w.setsampwidth(2)
        w.setframerate(rate)
        w.writeframes(b"\x00\x00" * channels * int(seconds * rate))


def voice_dir(tmp_path, seconds=8.0, rate=24_000, channels=1, transcript="Hello there."):
    write_wav(tmp_path / "reference.wav", seconds, rate, channels)
    (tmp_path / "reference.txt").write_text(transcript)
    return tmp_path


def test_accepts_a_good_reference(tmp_path):
    ref = load_reference(voice_dir(tmp_path, transcript="Hello\n  there.\n"))
    assert ref.audio.seconds == pytest.approx(8.0)
    assert ref.transcript == "Hello there."


def test_missing_clip_says_to_record(tmp_path):
    with pytest.raises(ValueError, match="make record"):
        load_reference(tmp_path)


@pytest.mark.parametrize(
    ("kwargs", "message"),
    [
        ({"rate": 44_100}, "sample rate is 44100 Hz"),
        ({"channels": 2}, "2 channels, need mono"),
        ({"seconds": 1.0}, "clip is 1.0 s"),
        ({"seconds": 30.0}, "clip is 30.0 s"),
        ({"transcript": "  \n"}, "is empty"),
    ],
)
def test_rejects_a_bad_reference(tmp_path, kwargs, message):
    with pytest.raises(ValueError, match=message):
        load_reference(voice_dir(tmp_path, **kwargs))

Detailed breakdown

  • write_wav builds a silent WAV file of any length, rate and channel count with the standard library, so every rejection path can be tested without a microphone or a model.
  • test_rejects_a_bad_reference is parametrized over the five ways a reference can be wrong, and matches on the start of each message. If one of the messages changes, the matching test fails.
  • test_missing_clip_says_to_record pins the error a new user sees first, which names the command that fixes it.

Run the tests:

uv run pytest tests/test_reference.py -v
tests/test_reference.py::test_accepts_a_good_reference PASSED            [ 14%]
tests/test_reference.py::test_missing_clip_says_to_record PASSED         [ 28%]
tests/test_reference.py::test_rejects_a_bad_reference[kwargs0-sample rate is 44100 Hz] PASSED [ 42%]
tests/test_reference.py::test_rejects_a_bad_reference[kwargs1-2 channels, need mono] PASSED [ 57%]
tests/test_reference.py::test_rejects_a_bad_reference[kwargs2-clip is 1.0 s] PASSED [ 71%]
tests/test_reference.py::test_rejects_a_bad_reference[kwargs3-clip is 30.0 s] PASSED [ 85%]
tests/test_reference.py::test_rejects_a_bad_reference[kwargs4-is empty] PASSED [100%]

============================== 7 passed in 0.01s ===============================

Step 5: Hear what a clip says

A clone has two jobs: say the right words, and say them in your voice. This step builds the check for the first. Whisper, running locally on MLX, transcribes a clip, and a word error rate compares the transcript with the text it should contain. The same check guards the recording in Step 7, where a reference clip that does not say its transcript would otherwise go unnoticed.

Word error rate (WER) is the standard score for this comparison. It is the number of word edits (dropped, added or swapped words) needed to turn the transcript back into the expected text, divided by the number of expected words. 0% is a perfect match. One wrong word in 32 is 3.1%.

Create the file

touch src/voiceclone/textcheck.py

Add the code: src/voiceclone/textcheck.py

"""Compare what was asked for with what a transcriber heard."""

import re


def words(text: str) -> list[str]:
    """Lowercase, drop punctuation, split on whitespace.

    Apostrophes inside words survive so "don't" stays one word.
    """
    text = text.lower().replace("’", "'")
    text = re.sub(r"[^a-z0-9' ]+", " ", text)
    return [w.strip("'") for w in text.split() if w.strip("'")]


def word_error_rate(expected: str, heard: str) -> float:
    """Word-level edit distance divided by the number of expected words."""
    ref, hyp = words(expected), words(heard)
    if not ref:
        return 0.0 if not hyp else 1.0
    prev = list(range(len(hyp) + 1))
    for i, r in enumerate(ref, start=1):
        cur = [i] + [0] * len(hyp)
        for j, h in enumerate(hyp, start=1):
            cur[j] = min(
                prev[j] + 1,  # a word was dropped
                cur[j - 1] + 1,  # a word was added
                prev[j - 1] + (r != h),  # a word was swapped, or matched
            )
        prev = cur
    return prev[-1] / len(ref)

Detailed breakdown

  • words normalizes before comparing. Whisper writes its own punctuation and capitalization (voice with no where your text had voice, with no), and neither is a speech error, so both are stripped. The curly apostrophe is folded into a straight one because Whisper and text editors disagree on which to use.
  • word_error_rate is a Levenshtein edit distance computed over words instead of characters. It keeps only two rows of the table at a time, so memory stays small even for a long text. The three branches of the min are the three kinds of edit, as the comments say.
  • The empty case is defined explicitly, so an empty text file cannot cause a division by zero.

Create the file

touch tests/test_textcheck.py

Add the code: tests/test_textcheck.py

import pytest

from voiceclone.textcheck import word_error_rate, words


def test_words_ignores_case_and_punctuation():
    assert words("Hello, World! It's 2026.") == ["hello", "world", "it's", "2026"]


def test_words_folds_curly_apostrophe():
    assert words("don’t") == ["don't"]


def test_identical_text_has_no_errors():
    assert word_error_rate("A Mac wrote this.", "a mac wrote this") == 0.0


@pytest.mark.parametrize(
    ("heard", "errors"),
    [
        ("the quick fox", 1),  # one word dropped
        ("the quick brown red fox", 1),  # one word added
        ("the quick crown fox", 1),  # one word swapped
        ("a slow crown dog", 4),  # every word wrong
    ],
)
def test_error_rate_counts_edits_per_expected_word(heard, errors):
    assert word_error_rate("the quick brown fox", heard) == errors / 4


def test_empty_expected_text():
    assert word_error_rate("", "") == 0.0
    assert word_error_rate("", "surprise") == 1.0

Detailed breakdown

  • The parametrized test has one case for each kind of edit, plus one where every word is wrong. Each expected value is the edit count divided by the four expected words, so you can check the arithmetic by eye.
  • The punctuation and apostrophe tests pin the normalization, which is what keeps a correct clone from scoring as an error.

Loading a model with mlx-audio prints progress lines to standard output, such as Loaded speech tokenizer from .... They would sit in the middle of every report this tool prints, so a small helper redirects them.

Create the file

touch src/voiceclone/quiet.py

Add the code: src/voiceclone/quiet.py

"""Keep model-loading chatter off the terminal."""

import contextlib
import io


@contextlib.contextmanager
def quiet():
    """Swallow what mlx-audio prints to stdout while it loads a model.

    Its loaders print progress lines ("Loaded speech tokenizer from ...") that
    would bury the measurements this tool reports. Errors still raise.
    """
    with contextlib.redirect_stdout(io.StringIO()):
        yield

Detailed breakdown

  • redirect_stdout captures only standard output. Warnings and exceptions go to standard error or propagate as usual, so a failed load is still loud.
  • It wraps model loading only. Everything the tool reports is printed after the with block ends.

Then the transcriber.

Create the file

touch src/voiceclone/listen.py

Add the code: src/voiceclone/listen.py

"""Transcribe a WAV file with Whisper, running locally on MLX."""

from pathlib import Path

from mlx_audio.stt.utils import load_model

from voiceclone.models import WHISPER_MODEL
from voiceclone.quiet import quiet


def transcribe(path: Path) -> str:
    with quiet():
        model = load_model(WHISPER_MODEL)
    return model.generate(str(path), language="en").text.strip()

Detailed breakdown

  • load_model here is mlx-audio’s speech-to-text loader. It finds the model in the Hugging Face cache that make download filled, and builds Whisper on MLX.
  • language="en" skips Whisper’s language detection, so a short clip cannot be misdetected as another language. Change it if you write in another language. Qwen3-TTS supports ten, listed in Troubleshooting.
  • .text.strip() drops the leading space Whisper puts on its first segment.

Run the tests so far:

make test

The seven reference tests from Step 4 run first. The run ends with:

tests/test_textcheck.py::test_words_ignores_case_and_punctuation PASSED  [ 53%]
tests/test_textcheck.py::test_words_folds_curly_apostrophe PASSED        [ 60%]
tests/test_textcheck.py::test_identical_text_has_no_errors PASSED        [ 66%]
tests/test_textcheck.py::test_error_rate_counts_edits_per_expected_word[the quick fox-1] PASSED [ 73%]
tests/test_textcheck.py::test_error_rate_counts_edits_per_expected_word[the quick brown red fox-1] PASSED [ 80%]
tests/test_textcheck.py::test_error_rate_counts_edits_per_expected_word[the quick crown fox-1] PASSED [ 86%]
tests/test_textcheck.py::test_error_rate_counts_edits_per_expected_word[a slow crown dog-4] PASSED [ 93%]
tests/test_textcheck.py::test_empty_expected_text PASSED                 [100%]

============================== 15 passed in 0.01s ==============================

Step 6: Wire up the command line

The recording step needs to run the reference check from Step 4 and the transcriber from Step 5, so the voiceclone command comes next, before there is anything to clone with. It is written once, in full, with all three subcommands. speak and check import their modules only when they run, so the command works now and those two subcommands start working when Steps 8 and 9 add the code behind them.

Create the file

uv init --package already created src/voiceclone/__init__.py; replace its contents, and create the CLI module beside it.

touch src/voiceclone/cli.py

Add the code: src/voiceclone/cli.py

"""Command line: `voiceclone reference`, `speak` and `check`."""

import argparse
from pathlib import Path

from voiceclone.models import TTS_MODEL
from voiceclone.reference import load_reference


def _reference(args: argparse.Namespace) -> int:
    ref = load_reference(args.voice)
    clip = ref.audio
    print(f"reference: {clip.path}")
    print(f"  format:     {clip.sample_rate} Hz, {clip.channels} channel, {clip.seconds:.2f} s")
    print(f"  transcript: {ref.transcript}")
    if not args.transcribe:
        return 0

    from voiceclone.listen import transcribe
    from voiceclone.textcheck import word_error_rate

    heard = transcribe(clip.path)
    wer = word_error_rate(ref.transcript, heard)
    print(f"  heard:      {heard}")
    print(f"  word error rate: {wer:.1%}")
    if wer > args.max_wer:
        print("FAIL: the clip does not say what reference.txt says; record it again")
        return 1
    print("PASS")
    return 0


def _speak(args: argparse.Namespace) -> int:
    from voiceclone.synth import clone

    reference = load_reference(args.voice)
    stats = clone(
        args.text.read_text(), reference, args.out, model_id=args.model, seed=args.seed
    )
    speed = stats.audio_seconds / stats.generate_seconds
    print(f"wrote {args.out}")
    print(f"  paragraphs: {stats.paragraphs}")
    print(f"  audio:      {stats.audio_seconds:.2f} s")
    print(f"  generation: {stats.generate_seconds:.2f} s ({speed:.1f}x real time)")
    print(f"  peak MLX memory: {stats.peak_memory_gb:.2f} GB")
    return 0


def _check(args: argparse.Namespace) -> int:
    from voiceclone.check import check

    reference = load_reference(args.voice)
    text = args.text.read_text()
    report = check(args.clip, text, reference, model_id=args.model)
    clip = report.clip
    print(f"clip:  {clip.path}")
    print(f"  format:   {clip.sample_rate} Hz, {clip.channels} channel, {clip.seconds:.2f} s")
    print(f"  expected: {' '.join(text.split())}")
    print(f"  heard:    {report.heard}")
    print(f"  word error rate: {report.wer:.1%}")
    print("speaker similarity to your reference (1.0 = identical):")
    print(f"  cloned clip:          {report.clone_similarity:.3f}")
    print(f"  same model, no clone: {report.baseline_similarity:.3f}")
    ok = report.wer <= args.max_wer and report.clone_similarity > report.baseline_similarity
    print("PASS" if ok else "FAIL")
    return 0 if ok else 1


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="voiceclone")
    parser.add_argument("--voice", type=Path, default=Path("voice"),
                        help="folder holding reference.wav and reference.txt")
    parser.add_argument("--model", default=TTS_MODEL, help="Qwen3-TTS Base checkpoint")
    sub = parser.add_subparsers(dest="command", required=True)

    ref = sub.add_parser("reference", help="validate the reference clip and transcript")
    ref.add_argument("--transcribe", action="store_true",
                     help="also check the clip says its transcript, using Whisper")
    ref.add_argument("--max-wer", type=float, default=0.05)
    ref.set_defaults(func=_reference)

    speak = sub.add_parser("speak", help="turn a text file into speech in your voice")
    speak.add_argument("text", type=Path, help="text file to read aloud")
    speak.add_argument("out", type=Path, help="WAV file to write")
    speak.add_argument("--seed", type=int, default=None, help="fix sampling for a repeatable take")
    speak.set_defaults(func=_speak)

    chk = sub.add_parser("check", help="verify a clip says the text, in your voice")
    chk.add_argument("clip", type=Path)
    chk.add_argument("text", type=Path, help="the text file the clip was made from")
    chk.add_argument("--max-wer", type=float, default=0.10)
    chk.set_defaults(func=_check)
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        return args.func(args)
    except (ValueError, FileNotFoundError) as err:
        print(f"error: {err}")
        return 2

Detailed breakdown

  • _reference prints what Step 4’s loader found. With --transcribe it also runs Whisper on the clip and fails if more than 5% of the words differ from reference.txt. A reference transcript has to be close to exact, which is why its threshold is half the one check uses for generated speech.
  • _speak loads the reference, hands the text to clone (Step 8) and reports how long the audio is, how long generation took, and the peak memory MLX used. The speed is audio seconds divided by generation seconds, so 6x means a minute of speech took about ten seconds to generate.
  • _check runs Step 9’s measurements and prints PASS only if both hold: the word error rate is within --max-wer, and the clip sounds more like your reference than the same model does without it. The exit code follows, so make check fails in a script the way a test would.
  • Imports inside the handlers are what let this file exist before synth.py and check.py do. They also keep voiceclone --help fast, since MLX and the models load only when a subcommand needs them.
  • main turns a ValueError or FileNotFoundError into a one-line message and exit code 2. Every problem the project detects on purpose, from a missing clip to an empty text file, raises ValueError, and a mistyped path raises FileNotFoundError, so you get a message instead of a traceback.

Add the code: src/voiceclone/__init__.py

import sys

from voiceclone.cli import main as _main


def main() -> None:
    sys.exit(_main())

Detailed breakdown

  • [project.scripts] in pyproject.toml points the voiceclone command at this main. sys.exit passes the handler’s return value out as the process exit code, which is what make checks.
  • cli.main takes an optional argv and returns an integer rather than exiting, so it can also be called from a test or another script.

Ask the new command for a reference before one exists. It should fail, and the message names the command that fixes it.

uv run voiceclone reference
error: voice/reference.wav not found; run `make record` first

Step 7: Record your reference clip

Now the one step only you can do: record yourself reading a fixed script. The quality of everything after this depends on the clip, so it is worth a minute to get right. Find a quiet room, keep the microphone at a steady distance, and read at your normal pace and pitch. Qwen3-TTS copies how you sound in this clip, including a rushed or flat reading.

The script is plain text, and it is also the transcript. make record copies it to voice/reference.txt, so the words you read and the words the model is told you read come from one file.

Create the file

touch script.txt

Add the code: script.txt

I'm recording this short clip so a speech model on my own Mac can learn how I
sound. Nothing in it leaves this machine, and I can delete it whenever I like.

Detailed breakdown

  • Short and plain on purpose. At a normal pace the two sentences take about 6 to 10 seconds, inside Step 4’s 3-to-20-second window, and they contain no names or numbers that a reader might say differently from how they are written.
  • Edit it if you like, but read exactly what the file says afterwards. The model lines your audio up with this text word by word (Step 8 shows how).
  • Saying what the clip is for, in the clip, is a small safeguard: a recording that announces it was made to train a speech model is harder to pass off as something else.

Pick the microphone

The record target reads from MIC, which defaults to default, the input macOS has selected. That is not always the microphone you think. Call and meeting apps often install a virtual input device, and if one of those is the system default you will record silence. List what ffmpeg sees:

make mics

It prints a heading and then one line per input device, such as [2] MacBook Pro Microphone. Pass the name, or the number, to record. The name is safer, because the numbers can change when a device is plugged in or removed.

Record

make record prints the script, starts ffmpeg, and about a second and a half later prints >>> Speak now. Wait for that line before you start reading. The recording stops by itself after 15 seconds, so finish reading and stay quiet until it ends. The first time you run it, macOS asks whether your terminal app may use the microphone. Allow it. If that first run recorded silence while the dialog was open, run the command again.

make record MIC="MacBook Pro Microphone"

The record recipe in the Makefile from Step 3 does four things, and two of them are there because a simpler version failed while this article was being written:

  • The recording pass. -f avfoundation selects AVFoundation, the macOS framework ffmpeg records through, and -i ":$(MIC)" names the device; the part before the colon would be a video device, so leaving it empty records audio only. -t 15 sits before -i, which makes it an input option: read 15 seconds from the microphone, then stop. -ac 1 -ar 24000 -c:a pcm_s16le writes mono, 24 kHz, 16-bit uncompressed PCM, exactly what Step 4 checks for.
  • ffmpeg starts in the background (&), the prompt prints 1.5 seconds later, and wait holds until ffmpeg exits. Opening the device takes a moment. Printing the prompt first, then starting ffmpeg, invites you to start speaking before anything is recording.
  • The trim runs as a second pass over voice/raw.wav. silenceremove removes the quiet lead-in, areverse flips the clip so the same filter can remove the quiet tail, and a second areverse flips it back. It is a separate pass because areverse has to hold the whole input before it can emit anything. An earlier one-pass version applied it to the live microphone with -t 15 after -i, which limits the output rather than the input, so the recording never ended.
  • It finishes with voiceclone reference --transcribe, so a bad recording is caught before you clone from it.

The first recording made for this article shows why the last check is there. An earlier version of the recipe printed the prompt too early, and the start of the script was lost:

reference: voice/reference.wav
  format:     24000 Hz, 1 channel, 6.79 s
  transcript: I'm recording this short clip so a speech model on my own Mac can learn how I sound. Nothing in it leaves this machine, and I can delete it whenever I like.
  heard:      clip so a speech model on my own Mac can learn how I sound. Nothing in it leaves this machine and I can delete it whenever I like.
  word error rate: 12.5%
FAIL: the clip does not say what reference.txt says; record it again

Every check in Step 4 passed. The clip was the right rate, mono, and nearly 7 seconds long, but four of the script’s 32 words were missing (4 / 32 = 12.5%). Cloning from that clip would have paired audio that starts at “clip” with a transcript that starts at “I’m”, which is the mismatch described above. Only a check that transcribes the clip can catch that.

The second recording passed:

Read this aloud after the Speak now prompt:

    I'm recording this short clip so a speech model on my own Mac can learn how I
    sound. Nothing in it leaves this machine, and I can delete it whenever I like.

>>> Speak now. Recording stops by itself after 15 seconds.
reference: voice/reference.wav
  format:     24000 Hz, 1 channel, 6.71 s
  transcript: I'm recording this short clip so a speech model on my own Mac can learn how I sound. Nothing in it leaves this machine, and I can delete it whenever I like.
  heard:      I'm recording a short clip so a speech model on my own Mac can learn how I sound. Nothing in it leaves this machine and I can delete it whenever I like.
  word error rate: 3.1%
PASS

One word differs: Whisper heard “a short clip” where the script says “this short clip”. That is 1 / 32 = 3.1%, inside the 5% allowance. The allowance exists because Whisper itself sometimes mishears a word, and a strict 0% would reject good recordings. If you prefer to be exact, listen to the clip with afplay voice/reference.wav and, if you really did say “a”, change voice/reference.txt to match. Your timings and wording will differ from the ones shown here.

Step 8: Generate speech paragraph by paragraph

With a validated clip in voice/, the cloning itself is a few lines. The part that matters is how Qwen3-TTS uses the clip, because it explains both why the transcript must be exact and why this code feeds the model one paragraph at a time.

The Base model clones in context. mlx-audio’s speech tokenizer encodes your clip into the 12.5-frames-per-second audio codes from Step 2, and the model’s prompt is built from three things:

  • your transcript followed by the new text,
  • your clip’s audio codes, and
  • a speaker embedding, a fixed-length vector summarizing what your voice sounds like, computed from the clip by the model’s speaker encoder, a component separate from the speech tokenizer.

Generation continues the audio codes from where your clip ends, speaking the new text. Because your transcript and your audio are lined up against each other in the prompt, a transcript that does not match the clip misleads the model about which sounds go with which words.

Create the file

touch src/voiceclone/synth.py

Add the code: src/voiceclone/synth.py

"""Generate speech in the reference voice with Qwen3-TTS on MLX."""

import re
import time
from dataclasses import dataclass
from pathlib import Path

import mlx.core as mx
import numpy as np
from mlx_audio.audio_io import write
from mlx_audio.tts.utils import load_model

from voiceclone.models import TTS_MODEL
from voiceclone.quiet import quiet
from voiceclone.reference import Reference

# Silence inserted between paragraphs, in seconds.
PARAGRAPH_GAP = 0.4


@dataclass(frozen=True)
class SynthStats:
    paragraphs: int
    audio_seconds: float
    generate_seconds: float
    peak_memory_gb: float


def paragraphs(text: str) -> list[str]:
    """Split on blank lines and unwrap each paragraph onto one line.

    In cloning mode the model voices whatever it is given in a single pass,
    newlines included, so the paragraphs are generated one call at a time.
    A line holding only spaces or tabs counts as blank.
    """
    chunks = [" ".join(p.split()) for p in re.split(r"\n\s*\n", text)]
    return [c for c in chunks if c]


def clone(
    text: str,
    reference: Reference,
    out_path: Path,
    model_id: str = TTS_MODEL,
    seed: int | None = None,
) -> SynthStats:
    """Speak `text` in the reference voice and write a 24 kHz mono WAV."""
    chunks = paragraphs(text)
    if not chunks:
        raise ValueError("the text file is empty")

    with quiet():
        model = load_model(model_id)
    if seed is not None:
        mx.random.seed(seed)
    mx.reset_peak_memory()

    gap = np.zeros(int(PARAGRAPH_GAP * model.sample_rate), dtype=np.float32)

    started = time.perf_counter()
    pieces = []
    for chunk in chunks:
        for result in model.generate(
            text=chunk,
            ref_audio=str(reference.audio.path),
            ref_text=reference.transcript,
            lang_code="english",
        ):
            pieces.append(np.asarray(result.audio, dtype=np.float32))
        pieces.append(gap)
    elapsed = time.perf_counter() - started

    audio = np.concatenate(pieces[:-1])  # no gap after the last paragraph
    out_path.parent.mkdir(parents=True, exist_ok=True)
    write(out_path, audio, model.sample_rate)
    return SynthStats(
        paragraphs=len(chunks),
        audio_seconds=len(audio) / model.sample_rate,
        generate_seconds=elapsed,
        peak_memory_gb=mx.get_peak_memory() / 1e9,
    )

Detailed breakdown

  • load_model(model_id) builds the Qwen3-TTS Base model from the cached checkpoint, along with its speech tokenizer and speaker encoder. Loading takes a couple of seconds and is not counted in the generation time.
  • One generate call per paragraph. mlx-audio’s generate has a split_pattern argument that defaults to splitting on newlines, but its cloning path never reads it and voices the whole input in a single pass. A long file sent in one call becomes one unbroken continuation, so the pauses you meant between paragraphs are left to chance. Splitting on blank lines puts the breaks where you put them. paragraphs also joins hard-wrapped lines inside a paragraph, so a line break mid-sentence does not reach the model.
  • The clip is encoded once. Every call passes the same clip and transcript, and mlx-audio caches the clip’s audio codes, keyed by transcript and clip, so later paragraphs skip the expensive encoding step. The speaker embedding is recomputed on each call, which is cheap.
  • PARAGRAPH_GAP inserts 0.4 seconds of silence between paragraphs, so they do not run together when the pieces are joined.
  • lang_code="english" tells the model which language the text is in, instead of leaving it to guess with auto.
  • Sampling is random. Qwen3-TTS picks each audio code at random from the likely candidates rather than always taking the most likely one, so two unseeded runs with the same input give different takes, with slightly different pacing and length. seed fixes MLX’s random state, which makes a take repeatable.
  • mx.reset_peak_memory zeroes MLX’s record of the most memory it has allocated at once, just before generation starts. The reported peak therefore covers generation, with the weights already loaded, and not the load itself.

Add a test for the paragraph splitter. It is the only part of this file that runs without a model.

Create the file

touch tests/test_synth.py

Add the code: tests/test_synth.py

from voiceclone.synth import paragraphs


def test_paragraphs_split_on_blank_lines_and_unwrap():
    text = "One line\nwrapped here.\n\n\nSecond   paragraph.\n"
    assert paragraphs(text) == ["One line wrapped here.", "Second paragraph."]


def test_a_line_of_spaces_still_separates_paragraphs():
    assert paragraphs("First.\n   \t\nSecond.") == ["First.", "Second."]


def test_paragraphs_of_blank_text_is_empty():
    assert paragraphs(" \n\n \n") == []

Detailed breakdown

  • The first test covers both things paragraphs does: three newlines in a row still make one break, and the wrapped first paragraph comes back as one line.
  • The second checks that a line holding only spaces or a tab still counts as blank. Editors often leave trailing whitespace, and splitting on a literal \n\n would silently merge those paragraphs into one call.
  • The third pins the empty case that makes clone raise the text file is empty instead of writing a silent file.

Now give it something to read. The sample text has two paragraphs, so you can hear the split.

Create the file

mkdir -p text
touch text/hello.txt

Add the code: text/hello.txt

This sentence was never spoken out loud. A speech model running on this Mac
wrote it from a short sample of my voice, with no cloud service involved.

A blank line starts a new paragraph, and the model voices each paragraph on
its own before the pieces are joined into one file.

Detailed breakdown

  • Two paragraphs, separated by a blank line, become two generate calls and one 0.4-second gap.
  • Hard-wrapped lines inside each paragraph check that paragraphs joins them before the model sees them.

Generate it:

make speak
uv run voiceclone speak text/hello.txt out/hello.wav
wrote out/hello.wav
  paragraphs: 2
  audio:      14.32 s
  generation: 2.25 s (6.4x real time)
  peak MLX memory: 6.69 GB

Fourteen seconds of speech took a little over two seconds on the review machine. Expect a smaller multiple on a smaller chip. The first generation in a new project is slower too: in a clean rebuild on the review machine it ran at 3.5x, and later runs at about 6x like the one above. The peak memory figure varied between 6.1 and 7.3 GB across runs. It is MLX’s count of memory it allocated, and macOS reported a smaller resident size for the same process (about 2.2 GB). The two measure different things, so plan for the larger, which is why the prerequisites ask for 16 GB. Listen to the result:

afplay out/hello.wav

You should hear your own voice saying something you never said. If you do not, see Troubleshooting before going further, because the check in the next step will not fix a bad reference clip.

Finally, see the sampling for yourself. The same seed twice gives byte-identical files, and a different seed gives a different take:

uv run voiceclone speak --seed 7 text/hello.txt out/take-a.wav
uv run voiceclone speak --seed 7 text/hello.txt out/take-b.wav
uv run voiceclone speak --seed 8 text/hello.txt out/take-c.wav
md5 out/take-*.wav
MD5 (out/take-a.wav) = ce42419879b7f3994f97b8afc3b57598
MD5 (out/take-b.wav) = ce42419879b7f3994f97b8afc3b57598
MD5 (out/take-c.wav) = 3d6d8386471243e1cbabba99d35a70c7

The two seed-7 takes were 13.76 seconds each and the seed-8 take was 14.40. Your hashes will differ from these, because your voice is a different input, but the pattern will not. When a take has a word you do not like, try another seed before you rewrite the text.

Step 9: Measure whose voice it is

Listening tells you whether a clone sounds right to you, but it is not a result you can write down, repeat, or check in a script. This step adds the measurement behind make check, which answers both of the questions a clone has to pass: whether it says the text, and whether it is in your voice.

The first question reuses Step 5’s Whisper and word error rate. The second needs a way to compare voices, and the model already has one: the speaker encoder from Step 8, which reduces any clip to a speaker embedding. Two clips of the same voice give embeddings that point in nearly the same direction, and the cosine similarity of two embeddings measures that directly. It is 1.0 when they point the same way, and lower as the voices differ.

A similarity score on its own does not mean much, because any two voices reading English can score high. So the check computes a baseline as well: the same model reading the same text with no reference clip at all. The clone passes only if it is closer to your voice than that baseline is, so the comparison isolates the one thing cloning was supposed to change.

Create the file

touch src/voiceclone/check.py

Add the code: src/voiceclone/check.py

"""Measure a generated clip: format, what Whisper hears, and whose voice it is."""

from dataclasses import dataclass
from pathlib import Path

import mlx.core as mx
import numpy as np
from mlx_audio.audio_io import read
from mlx_audio.tts.utils import load_model as load_tts

from voiceclone.listen import transcribe
from voiceclone.models import TTS_MODEL
from voiceclone.quiet import quiet
from voiceclone.reference import Reference, WavInfo, wav_info
from voiceclone.textcheck import word_error_rate


@dataclass(frozen=True)
class Report:
    clip: WavInfo
    heard: str
    wer: float
    clone_similarity: float
    baseline_similarity: float


def _embedding(tts, audio: np.ndarray) -> np.ndarray:
    vec = np.asarray(tts.extract_speaker_embedding(mx.array(audio))).reshape(-1)
    return vec / np.linalg.norm(vec)


def _load_mono(path: Path) -> np.ndarray:
    audio, _ = read(str(path))
    audio = np.asarray(audio, dtype=np.float32)
    return audio.mean(axis=1) if audio.ndim > 1 else audio


def check(
    clip_path: Path, text: str, reference: Reference, model_id: str = TTS_MODEL
) -> Report:
    """Score `clip_path` against the text it should say and the voice it should have.

    The baseline is the same model reading the same text with no reference,
    so the two similarity scores differ mainly in whether cloning happened.
    """
    if not clip_path.exists():
        raise ValueError(f"{clip_path} not found; run `make speak` first")
    if not text.split():
        raise ValueError("the text file is empty")
    heard = transcribe(clip_path)

    with quiet():
        tts = load_tts(model_id)
    mx.random.seed(0)
    baseline = np.concatenate(
        [
            np.asarray(r.audio, dtype=np.float32)
            for r in tts.generate(text=" ".join(text.split()), lang_code="english")
        ]
    )
    ref_vec = _embedding(tts, _load_mono(reference.audio.path))
    return Report(
        clip=wav_info(clip_path),
        heard=heard,
        wer=word_error_rate(text, heard),
        clone_similarity=float(ref_vec @ _embedding(tts, _load_mono(clip_path))),
        baseline_similarity=float(ref_vec @ _embedding(tts, baseline)),
    )

Detailed breakdown

  • _embedding runs mlx-audio’s extract_speaker_embedding and scales the result to unit length. For two unit vectors the dot product is the cosine similarity, so ref_vec @ ... is the whole comparison.
  • _load_mono reads a WAV file as floating-point samples and averages the channels if there is more than one. It does not resample. That is safe only because Step 4 guarantees the reference is 24 kHz, and the model always writes 24 kHz.
  • The baseline is generated by calling generate without ref_audio or ref_text, which makes the Base model speak in a default voice of its own. mx.random.seed(0) fixes that take, so the baseline score is the same every time you check the same text.
  • The baseline text is joined onto one line with " ".join(text.split()). Outside cloning mode generate does split on newlines, so without the join it would treat every wrapped line as its own segment. The baseline also differs from the clone in small ways (one call instead of one per paragraph, seed 0, a lower repetition penalty), which is why the docstring says the scores differ mainly in whether cloning happened.
  • The caveat. This is the same speaker encoder the model used to condition on your voice in Step 8. A high score therefore means the clone matches your voice as this model represents it, which is a consistency check, not an independent biometric judgment. The baseline is what makes the number useful; the absolute value is not a measure of how much the clone sounds like you to a person.

Run the check on the clip from Step 8:

make check
uv run voiceclone check out/hello.wav text/hello.txt
clip:  out/hello.wav
  format:   24000 Hz, 1 channel, 14.32 s
  expected: This sentence was never spoken out loud. A speech model running on this Mac wrote it from a short sample of my voice, with no cloud service involved. A blank line starts a new paragraph, and the model voices each paragraph on its own before the pieces are joined into one file.
  heard:    This sentence was never spoken out loud. Speech model running on this Mac wrote it from a short sample of my voice with no cloud service involved. A blank line starts a new paragraph and the model voices each paragraph on its own before the pieces are joined into one file.
  word error rate: 1.9%
speaker similarity to your reference (1.0 = identical):
  cloned clip:          0.989
  same model, no clone: 0.921
PASS

Reading the report from the top:

  • The format line confirms the clip is the 24 kHz mono WAV the code wrote, and its 14.32 seconds match what make speak reported.
  • One word is missing. The heard text starts its second sentence at “Speech model”, without the “A”. The text has 52 words, so one miss is 1 / 52 = 1.9%, well inside the 10% allowance. Whether the clone dropped the word or Whisper missed a short unstressed one, the sampled take is the cheap thing to change: if a word matters, generate another take with a different --seed and check again.
  • The similarity scores put the clone at 0.989 and the uncloned model at 0.921. Across seven takes of this text on the review machine, the clone scored between 0.984 and 0.989, and every make check run on this text put the baseline at 0.921.

Your numbers will differ, because your voice and every sampled take are different inputs. What should hold is the shape: a word error rate near zero, and a clone score clearly above the baseline.

Step 10: Read any text file in your voice, offline

Everything is in place, so this is the promise from the opening: a new text file, read aloud in your voice, checked, with nothing fetched from the network. The Makefile already sets HF_HUB_OFFLINE=1 (Step 3), and Hugging Face’s libraries honor it: any attempt to reach the Hub fails instead of going out, so a run that succeeds proves both models came from your disk. uv has a matching switch, UV_OFFLINE=1, which stops uv run from checking for packages. Commands you run straight through uv run voiceclone, like the seed comparison in Step 8, do not get the Makefile’s setting; prefix them with HF_HUB_OFFLINE=1 to keep them offline too.

Create the file

touch text/note.txt

Add the code: text/note.txt

Reminder for Thursday: the build server reboots at noon, so push your
branches before lunch.

If a test fails after the reboot, run it again once before you file a bug.

Detailed breakdown

  • Any text file works. Separate paragraphs with a blank line and wrap lines however you like. Step 8’s paragraphs handles both.
  • OUT follows TEXT, so this file becomes out/note.wav without naming it.

Clone it and check it in one make invocation, offline:

UV_OFFLINE=1 make speak check TEXT=text/note.txt
uv run voiceclone speak text/note.txt out/note.wav
wrote out/note.wav
  paragraphs: 2
  audio:      10.00 s
  generation: 1.64 s (6.1x real time)
  peak MLX memory: 6.36 GB
uv run voiceclone check out/note.wav text/note.txt
clip:  out/note.wav
  format:   24000 Hz, 1 channel, 10.00 s
  expected: Reminder for Thursday: the build server reboots at noon, so push your branches before lunch. If a test fails after the reboot, run it again once before you file a bug.
  heard:    Reminder for Thursday, the build server reboots at noon, so push your branches before lunch. If a test fails after the reboot, run it again once before you file a bug.
  word error rate: 0.0%
speaker similarity to your reference (1.0 = identical):
  cloned clip:          0.988
  same model, no clone: 0.949
PASS
afplay out/note.wav

That is the whole loop: a text file you wrote, spoken in your voice, with a report showing Whisper heard every word (it dropped the colon, and the comparison ignores punctuation) and that the clip is closer to your voice than the uncloned model. The baseline is 0.949 here against 0.921 in Step 9, because each new text gets a fresh baseline take, so compare the two scores within one report rather than across reports.

To see that offline mode is a real guard rather than a no-op, move a model out of the cache and run the check again. On the review machine, with the Whisper folder moved aside, voiceclone check stopped with huggingface_hub.errors.LocalEntryNotFoundError: Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and outgoing traffic has been disabled. Move the folder back (or run make download) and it passes again.

Run the full test suite one last time:

make test

It ends with 18 passed: seven from Step 4, eight from Step 5 and three from Step 8.

Troubleshooting

make record saves a clip that is rejected as 0.0 s. The trim removed everything, which means ffmpeg recorded silence. Either the terminal app has no microphone permission (check System Settings → Privacy & Security → Microphone), or MIC points at a virtual device. Run make mics and pass a real microphone’s name.

make record never stops. If you edited the recipe, check that -t 15 is still before -i, and that the silence trim is still a separate second pass. Applied to the live microphone, areverse holds all output back until the input ends, which a microphone never does. Press Ctrl-C to stop it.

The reference check prints FAIL. Compare the heard line with the transcript line. Missing words at the start usually mean you began reading before >>> Speak now., so record again. A single different word that you really did say is fixed by editing voice/reference.txt to match the clip, then re-running uv run voiceclone reference --transcribe.

The clone does not sound like you. Work through the reference clip first, because it is the input that matters most: record in a quieter room, keep a steady distance from the microphone, and read the way you normally speak. Then try the larger checkpoint. Download it with uv run hf download mlx-community/Qwen3-TTS-12Hz-1.7B-Base-8bit and pass the same --model to both commands, so the check measures with the encoder that did the cloning:

uv run voiceclone --model mlx-community/Qwen3-TTS-12Hz-1.7B-Base-8bit speak text/hello.txt out/hello-1.7b.wav
uv run voiceclone --model mlx-community/Qwen3-TTS-12Hz-1.7B-Base-8bit check out/hello-1.7b.wav text/hello.txt

ValueError: Processor not found from the transcriber means the Whisper repository has no tokenizer files. Use mlx-community/whisper-large-v3-turbo-asr-fp16, as in models.py, rather than mlx-community/whisper-large-v3-turbo.

CustomVoice model requires 'voice' (speaker name) means --model names a CustomVoice checkpoint. Only Base checkpoints clone.

LocalEntryNotFoundError ... outgoing traffic has been disabled means a model is missing from the cache while offline mode is on, which it always is under make. Run make download, the one target that goes online.

make check fails on an extra word at the start of a paragraph. The opening of a paragraph is where generated speech goes wrong most often. On the review machine, a two-word paragraph (“Beta paragraph.”) came out as “like beta paragraph” in 3 of 3 runs (50% word error rate), and a full-sentence paragraph picked up a leading “the” in 1 of 4. Give each paragraph at least one full sentence, and if a take has a stray word, try another --seed.

Text in another language. Qwen3-TTS speaks Chinese, English, French, German, Italian, Japanese, Korean, Portuguese, Russian and Spanish. Three constants assume English: lang_code="english" in synth.py and check.py, and language="en" in listen.py. Qwen3-TTS takes the full lowercase name (french), and Whisper takes the two-letter code (fr). Change all three, and record your reference in the language you will generate, since the transcript and the clip must match.

Makefile: *** missing separator. A recipe line starts with spaces. Make requires a tab.

Recap

You recorded about seven seconds of your voice and now have a command that reads any text file aloud in it, on your Mac, with no hosted service and with offline mode on for every run once the models are cached. Along the way:

  • Qwen3-TTS clones in context. The Base model takes your clip, its exact transcript and a speaker embedding, and continues in your voice with no training. That is why the transcript has to match, and why a bad recording is worth redoing.
  • The recording is checked before it is used. make record validates the format and length, then has Whisper confirm the clip says its transcript, which caught a recording that every format check passed.
  • Long text is generated one paragraph at a time, because mlx-audio’s cloning path ignores its own line splitting.
  • Takes are sampled. --seed makes one repeatable, and a different seed is the quickest fix for a bad word.
  • The result is measured, not just heard. make check reports the word error rate from a Whisper transcript, and scores the clip against your voice next to an uncloned baseline from the same model.

Your recording and everything made from it stay in voice/ and out/, which git ignores. Delete both folders when you no longer want a model to be able to sound like you; nothing else in the project holds a copy.

Possible next steps:

  • Batch a folder of text files by looping over make speak TEXT=....
  • Keep the model loaded between files, so the reference is encoded once per session instead of once per run.
  • Try the 1.7B checkpoint and compare make check scores for your own voice.