---
title: tts-zh-en-onnx
canonical_url: "https://www.modelscope.cn/models/QuadraV/tts-zh-en-onnx"
md_url: "https://www.modelscope.cn/models/QuadraV/tts-zh-en-onnx.md"
repository: QuadraV/tts-zh-en-onnx
chinese_name: "中英文tts onnx推理（本地化部署）"
last_updated: 2024-11-05
pipeline_tag: text-to-speech
tasks:
  - text-to-speech
library_name:
  - onnx
  - other
frameworks:
  - other
downloads: 2890
stars: 1
---

# tts-zh-en-onnx

> tts-zh-en-onnx - QuadraV 在 ModelScope 开源的模型。

- **Repository**: QuadraV/tts-zh-en-onnx
- **Tasks**: text-to-speech
- **Downloads**: 2890
- **Stars**: 1
- **Last updated**: 2024-11-05

Source: https://www.modelscope.cn/models/QuadraV/tts-zh-en-onnx

---

# Introduction


推理代码如下：

```python
import threading
import time
import queue
import numpy as np
import sounddevice as sd
import sherpa_onnx

class TTS:
    def __init__(self, model_path, 
                 tokens_path, 
                 lexicon_path=None, 
                 data_dir="", 
                 dict_dir="", 
                 provider="cpu", 
                 num_threads=2, 
                 debug=False):
        self.sample_rate = None
        self.audio_queue = queue.Queue()
        self.audio_count = 0
        self.playback_thread = threading.Thread(target=self._playback_worker, daemon=True)
        self.playback_thread.start()

        # Log initialization process
        self.log(f"Initializing TTS with model: {model_path}, tokens: {tokens_path}, lexicon: {lexicon_path}")

        tts_config = sherpa_onnx.OfflineTtsConfig(
            model=sherpa_onnx.OfflineTtsModelConfig(
                vits=sherpa_onnx.OfflineTtsVitsModelConfig(
                    model=model_path,
                    lexicon=lexicon_path,
                    data_dir=data_dir,
                    dict_dir=dict_dir,
                    tokens=tokens_path,
                ),
                provider=provider,
                debug=debug,
                num_threads=num_threads,
            ),
            rule_fsts="",
            max_num_sentences=1,
        )

        if not tts_config.validate():
            raise ValueError("Please check your config")

        # Log successful model loading
        self.log(f"Model loaded successfully, sample rate: {self.sample_rate}")

        self.tts = sherpa_onnx.OfflineTts(tts_config)
        self.sample_rate = self.tts.sample_rate

    def log(self, msg):
        print(msg)

    def check_queue(self):
        queue_size = self.audio_queue.qsize()
        self.log(f"Audio queue size: {queue_size}")
        return queue_size

    def generate(self, text, sid=0, speed=1.0):
        self.log(f"Generating speech for text: {text} | speed: {speed} | speaker id: {sid}")
        
        start_time = time.time()
        audio = self.tts.generate(
            text,
            sid=sid,
            speed=speed,
        )
        end_time = time.time()

        if len(audio.samples) == 0:
            self.log("Error: No audio samples generated.")
            return

        elapsed_seconds = end_time - start_time
        audio_duration = len(audio.samples) / audio.sample_rate
        real_time_factor = elapsed_seconds / audio_duration

        # Log the generation stats
        self.log(f"Audio generated successfully. Duration: {audio_duration:.2f}s | "
                 f"Generation Time: {elapsed_seconds:.2f}s | Real-time factor: {real_time_factor:.2f}")

        # Put the generated audio into the playback queue
        self.audio_queue.put(audio)
        self.audio_count += 1
        self.log(f"Audio added to queue. Queue size is now: {self.audio_queue.qsize()}")

    def _playback_worker(self):
        self.log("Playback worker started.")
        with sd.OutputStream(samplerate=self.sample_rate, channels=1, dtype='float32') as output_stream:
            while True:
                if self.audio_queue.qsize():
                    audio = self.audio_queue.get()
                    if audio is None:
                        self.log("Playback worker received stop signal.")
                        break
                    # Convert samples to float32 if necessary
                    samples = np.array(audio.samples, dtype='float32')
                    output_stream.write(samples)
                    self.audio_count -= 1
                    self.log(f"Audio played back. Queue size is now: {self.audio_queue.qsize()}")

                time.sleep(0.1)

    def stop(self):
        self.log("Stopping TTS system and waiting for playback thread to finish.")
        # Stop the playback thread gracefully
        self.audio_queue.put(None)
        self.playback_thread.join()
        self.log("Playback thread finished. TTS system stopped.")

if __name__ == "__main__":
    tts = TTS(
        model_path=r"./model.onnx",
        tokens_path=r"./tokens.txt",
        lexicon_path=r"./lexicon.txt",
        dict_dir=r"./dict"
    )

    try:
        # Generate multiple pieces of audio and add them to the queue
        tts.generate("我爱你中国 中国是一个古老的国家。", speed=0.8)
        tts.generate("中国是一个美丽的国度。", speed=0.8)
        tts.generate("有什么问题可以继续问我。", speed=0.8)
    finally:
        tts.stop()
```
