如何在 iPhone 的 SwiftUI 應用程式整合 LinnetTTS,生成離線語音回覆
Offline voice replies on iPhone: LinnetTTS integration in SwiftUI
文章示範在 iPhone 的 SwiftUI 應用程式整合 LinnetTTS,讓 41M 參數的神經 TTS 在裝置上串流生成 24 kHz 語音;83 MB fp16 權重只需在下載時連接網絡。
If you're building an iOS feature that speaks to the user (accessibility read-aloud, assistant replies, interactive storytelling), the default path is a cloud TTS API (OpenAI, ElevenLabs, Google) over the network. That works until the user is on a subway, or you need sub-100 ms time to first audio, or you want a privacy guarantee you can show a regulator.
This is a walkthrough of integrating LinnetTTS on iPhone. It's a streaming on-device neural TTS from VoxRT, 41M parameters, 83 MB of fp16 weights, 24 kHz output. The Swift package ships an xcframework (ios-arm64 and simulator slices) plus a one-screen SwiftUI sample. Everything runs locally; the network is only needed once to download the weights.
What you get, measured
On a stock iPhone 13 Pro Max (A15), one thread: step time 5.5 ms, real-time factor 7%. On an iPhone 11 (A13), one thread: step time 6.7-7.1 ms, RTF 8-9%. First chunk after 80 ms of model work plus the prime pass (about 30 ms with prepared voices). From cold tap to first speaker sample: 0.4-0.5 seconds on iPhone 11, including the OS audio route open.
Memory: about 85 MB resident for the model, plus ~20 MB per active streaming session for the KV caches. The static library adds about 2 MB to an arm64 app binary.
Languages: English only at this release. If you ship in other locales, this won't fit yet.
Dependency
In Xcode 15+, add the Swift package:
// Package.swift or Xcode project > Package Dependencies
.package(url: "https://github.com/VoxRT/LinnetTTS.git", from: "0.1.0")
Deployment target: iOS 15 or later. No CocoaPods path; SwiftPM only.
Weights
The 83 MB fp16 weights file, tokenizer, and two built-in voices (linnet-en-f1.npy female English, linnet-en-m1.npy male English) are distributed separately from the package (model files don't belong in a Git repo). Download the weights-v1 release bundle from the LinnetTTS GitHub releases:
linnet-en-35m.fp16.safetensors 83 MB runtime weights
tokenizer.model SentencePiece model
voices/linnet-en-f1.npy female English voice
voices/linnet-en-m1.npy male English voice
Bundle them into your app's resource folder (make sure they're added to your target → Build Phases → Copy Bundle Resources), or download on first launch and cache in the Documents directory. For user-facing apps, the first-launch download pattern is cleaner: the App Store binary stays small, and users only pay the 83 MB cost once.
Minimal integration, synchronous synthesis
For a non-streaming "generate a full utterance, play it" flow. The code below assumes it runs inside a throwing function (func loadAndSpeak() throws { ... }) or wrapped in do { ... } catch { ... }:
import LinnetTTS
import Foundation
let weights = Bundle.main.url(forResource: "linnet-en-35m.fp16", withExtension: "safetensors")!
let tokenizer = Bundle.main.url(forResource: "tokenizer", withExtension: "model")!
let voicePath = Bundle.main.url(forResource: "linnet-en-f1", withExtension: "npy")!
let model = try LinnetModel(weightsURL: weights, tokenizerURL: tokenizer)
let voice = try model.loadVoice(url: voicePath)
let audio: [Float] = try model.synthesize(
text: "Streaming TTS that fits in your pocket.",
voice: voice,
params: SynthParams(temp: 0.3, cfg: 2.0, seed: 0)
)
audio is a float array at 24 kHz mono, ready to feed into AVAudioPlayerNode (wrap as AVAudioPCMBuffer with pcmFormatFloat32, sampleRate 24000, channels 1) or write to a WAV file.
Model creation costs a few hundred milliseconds and should run off the main thread. loadVoice runs the voice through the model once and caches the result, so later sessions skip the voice part of the prime pass (about 39 ms on recent Apple cores, longer on A-series).
Streaming, first chunk in under 100 ms
For interactive UX where the user hears the start of the sentence while the model is still generating the rest. Run the loop below on a background queue, not on main:
let session = try model.session(voice: voice, params: SynthParams(seed: 0))
let player = try LinnetPlayer(sampleRate: model.sampleRate)
try session.prime(text: "Streaming gives you the first chunk after one step.")
while let chunk = try session.step() {
try player.write(chunk)
}
player.drain()
Each session.step() returns 1920 samples at 24 kHz, which is 80 ms of audio per step. The first chunk is slightly shorter (1200 samples), and the last chunk is 720 zeros. That's the streaming contract: concatenating all chunks gives bit-identical output to synthesize.
LinnetPlayer wraps AVAudioEngine and AVAudioPlayerNode. It queues up to 8 seconds of audio by default, so on a fast device the generator runs ahead at full speed and playback drains behind. write blocks if the buffer exceeds that window, which naturally paces the generator to real time in long utterances.
Threads on Apple platforms
Default is one thread. The runtime tunes this for phones: the A-series step is already 5-7 ms and splits into ~80 tiny regions, so waking a worker on a second performance core costs more than the work it saves. The README reports A13 with 2 threads = 11.4 ms per step vs 6.7 ms with 1 thread. On an M-series Mac, two threads do pay off (about 1.7x), but set that explicitly via model.threads = 2 since the default assumes a phone.
Audio is bit-identical for every thread count; only speed changes.
Honest trade-offs
What doesn't fit:
- English only. No multilingual support in this release.
-
Built-in voices are free; custom voice cloning is a paid service. The runtime is Apache-2.0 and the weights are openly available with a free commercial license for the two built-in voices. Voice cloning and model training are licensed separately (see
WEIGHTS_LICENSE.mdin the repo). - 83 MB download + 85 MB resident. Non-trivial for low-end hardware; compatible with any device on iOS 15 or later.
-
Streaming only in one direction. No ability to interrupt mid-utterance with a new one; you call
stop()on the player and start a fresh session.
Where to go next
The LinnetTTS repo has a complete SwiftUI sample app at bindings/ios/Sample/ (single screen: text box, Speak button, Stop button, step timings). Clone the repo, run bindings/ios/build-xcframework.sh, open Sample/LinnetSample.xcodeproj in Xcode, and you have a working TTS app on your device in about 10 minutes (plus the weights download).
Repo: https://github.com/VoxRT/LinnetTTS
Sample: bindings/ios/Sample/
Streaming contract: docs/streaming-contract.md
If you ship an iOS feature on top of this (accessibility, assistants, read-aloud), I'd be curious how latency and footprint compare to what you were using before.
來源:DEV Community · dev.to