Skip to content

Enable return value in callback for TTS in Go API. - #3150

Merged
csukuangfj merged 2 commits into
k2-fsa:masterfrom
csukuangfj:fix-go-tts
Feb 6, 2026
Merged

csukuangfj merged 2 commits into
k2-fsa:masterfrom
csukuangfj:fix-go-tts

Conversation

@csukuangfj

@csukuangfj csukuangfj commented Feb 6, 2026 •

Copy link
Copy Markdown
Collaborator

Also, add demo for tts playback

Summary by CodeRabbit

  • New Features

    • Real-time audio playback for TTS output
    • Graceful application termination via Ctrl+C
  • Refactor

    • Improved internal audio/callback flow and added model metadata accessors
  • Chores

    • Updated Go module to version 1.24.0
    • Standardized example script references and disabled debug output in example invocations

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Feb 6, 2026
@csukuangfj csukuangfj changed the title Enable return value in callback for tts in Go API. Enable return value in callback for TTS in Go API. Feb 6, 2026
@coderabbitai

coderabbitai Bot commented Feb 6, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds real-time audio playback to the offline TTS example (Oto + io.Pipe), updates Go versions to 1.24.0, changes TTS callback signatures to return bool for continuation, exposes OfflineTts.NumSpeakers() and SampleRate(), and redirects several test script paths to offline-tts-play.

Changes

Cohort / File(s) Summary
Go Module Version Updates
go-api-examples/offline-tts-play/go.mod, scripts/go/_internal/offline-tts-play/go.mod
Bump Go version from 1.17 to 1.24.0.
Offline TTS Play Implementation
go-api-examples/offline-tts-play/main.go, go-api-examples/offline-tts-play/run-matcha-zh.sh
Add real-time playback using Oto with an io.Pipe, goroutine-driven TTS generation, signal handling, and disable debug in the run script.
Test Script Path Redirections
scripts/go/_internal/offline-tts-play/run-*.sh (multiple files)
Update referenced script paths from non-streaming-tts/... to offline-tts-play/... across Kokoro/Matcha/VITS variants.
Go bindings / API changes
scripts/go/sherpa_onnx.go
Change generated-audio and progress callback types to return bool; update cgo wrappers to respect the boolean. Add OfflineTts.NumSpeakers() and OfflineTts.SampleRate() accessors.

Sequence Diagram

sequenceDiagram
    participant App as Main App
    participant Gen as TTS Generator (goroutine)
    participant Pipe as io.Pipe
    participant Player as Oto Player
    participant Audio as Audio Output

    App->>App: create Oto context & player
    App->>Pipe: create reader/writer
    App->>Player: wire pipe reader & start playback
    App->>Gen: launch generator goroutine

    par generation & playback
        Gen->>Gen: GenerateWithCallback -> produce samples
        Gen->>Gen: clamp & encode to 16-bit LE PCM
        Gen->>Pipe: write PCM chunks
    and
        Player->>Pipe: read PCM chunks
        Player->>Audio: stream to audio device
    end

    Gen->>App: close writer & signal done
    App->>App: wait for stop or completion, drain, shutdown
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 Hop, hop, the bytes now play,
Pipes hum softly, night and day.
Callbacks nod with boolean cheer,
Speakers sing — the rabbit's near! 🎶

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the primary change: enabling return values in TTS callbacks in the Go API. It is specific and directly related to the main modifications in scripts/go/sherpa_onnx.go.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello @csukuangfj, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly improves the Go API for Text-to-Speech by introducing a mechanism for callbacks to control the audio generation flow, enabling more dynamic and responsive applications. Additionally, it provides a practical, ready-to-use example of how to stream and play generated TTS audio in real-time, enhancing the overall utility and demonstration of the TTS capabilities.

Highlights

  • Enhanced TTS Callback Functionality: The tts.GenerateWithCallback function in the Go API now supports a boolean return value from its callback, allowing the generation process to be stopped prematurely if the callback returns false.
  • New Offline TTS Playback Demo: A new example (go-api-examples/offline-tts-play/main.go) has been added to demonstrate real-time audio playback of generated TTS output using the oto library, including graceful shutdown via signal handling.
  • New OfflineTts Methods: The OfflineTts struct in the Go API now includes NumSpeakers() and SampleRate() methods, providing direct access to the number of speakers and the sample rate of the loaded TTS model.
  • Go Version Update: The Go module files for the offline-tts-play example have been updated to use Go version 1.24.0.
Changelog
  • go-api-examples/offline-tts-play/go.mod
    • Updated Go version from 1.17 to 1.24.0.
  • go-api-examples/offline-tts-play/main.go
    • Added imports for audio playback and signal handling (e.g., oto, os/signal, io).
    • Implemented real-time audio playback of TTS output using the oto library.
    • Integrated io.Pipe to stream audio data from the TTS callback to the audio player.
    • Added Ctrl+C signal handling for graceful termination during audio playback.
    • Modified the tts.GenerateWithCallback usage to run in a goroutine and utilize the new boolean return value from the callback to manage streaming.
  • go-api-examples/offline-tts-play/run-matcha-zh.sh
    • Changed the --debug flag value from 1 to 0.
  • scripts/go/_internal/offline-tts-play/go.mod
    • Updated Go version from 1.17 to 1.24.0.
  • scripts/go/_internal/offline-tts-play/run-kokoro-en.sh
    • Updated script path to reference offline-tts-play example.
  • scripts/go/_internal/offline-tts-play/run-kokoro-zh-en.sh
    • Updated script path to reference offline-tts-play example.
  • scripts/go/_internal/offline-tts-play/run-matcha-en.sh
    • Updated script path to reference offline-tts-play example.
  • scripts/go/_internal/offline-tts-play/run-matcha-zh.sh
    • Updated script path to reference offline-tts-play example.
  • scripts/go/_internal/offline-tts-play/run-vits-ljs.sh
    • Updated script path to reference offline-tts-play example.
  • scripts/go/_internal/offline-tts-play/run-vits-piper-en_US-lessac-medium.sh
    • Updated script path to reference offline-tts-play example.
  • scripts/go/_internal/offline-tts-play/run-vits-vctk.sh
    • Updated script path to reference offline-tts-play example.
  • scripts/go/_internal/offline-tts-play/run-vits-zh-aishell3.sh
    • Updated script path to reference offline-tts-play example.
  • scripts/go/sherpa_onnx.go
    • Modified sherpaOnnxGeneratedAudioCallbackWithArg and sherpaOnnxGeneratedAudioProgressCallbackWithArg type definitions to return a boolean.
    • Updated _cgoGeneratedAudioCallback and _cgoGeneratedAudioProgressCallback to check the boolean return value from the Go callback and propagate it to the C side.
    • Added new methods NumSpeakers() and SampleRate() to the OfflineTts struct.
Activity
  • No specific activity (comments, reviews, etc.) has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a valuable enhancement to the Go TTS API by allowing the callback to return a value, which provides better control over the audio generation stream. The new offline-tts-play example is a great addition, clearly demonstrating how to stream and play TTS audio as it's generated. The code is well-structured and uses Go's concurrency patterns effectively. I have one suggestion to improve the shutdown logic in the new example by removing a redundant sleep.

Comment on lines +139 to +140
// let remaining audio drain
time.Sleep(500 * time.Millisecond)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This time.Sleep is not necessary to ensure the audio drains completely. The player.Close() call, which is deferred on line 97, is a blocking call that waits for the audio stream to be fully played, as per the oto library's documentation. Removing this sleep will make the shutdown logic cleaner and more robust.

@csukuangfj
csukuangfj merged commit 158d7d2 into k2-fsa:master Feb 6, 2026
1 check passed
@csukuangfj
csukuangfj deleted the fix-go-tts branch February 6, 2026 03:50

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR enhances the Go API for TTS functionality by enabling return value handling in callbacks and adding a new demo for real-time TTS audio playback.

Changes:

  • Modified TTS callback signatures to return bool values, allowing callers to control generation continuation
  • Added accessor methods (NumSpeakers, SampleRate) to the OfflineTts type
  • Created a new demo that plays generated TTS audio in real-time using the oto audio library with signal handling support
  • Updated shell script references from non-streaming-tts to offline-tts-play for consistency

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
scripts/go/sherpa_onnx.go Updated callback type signatures to return bool and implemented proper return value mapping to C API (1=continue, 0=stop); added NumSpeakers() and SampleRate() accessor methods
go-api-examples/offline-tts-play/main.go Implemented real-time audio playback demo with streaming TTS output, audio format conversion, signal handling, and goroutine-based concurrent processing
go-api-examples/offline-tts-play/go.mod Updated Go version to 1.24.0
scripts/go/_internal/offline-tts-play/go.mod Updated Go version to 1.24.0
go-api-examples/offline-tts-play/run-matcha-zh.sh Changed debug flag from 1 to 0
scripts/go/_internal/offline-tts-play/run-*.sh Updated script paths to reference offline-tts-play instead of non-streaming-tts

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

<-ready

// Pipe: TTS writes → Oto reads
pr, pw := io.Pipe()

Copilot AI Feb 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pipe reader (pr) is never explicitly closed. When the main function exits, the player.Close() will close the player, but the pipe reader itself should be closed to prevent potential resource leaks. Consider adding a defer statement like "defer pr.Close()" after creating the pipe, or closing pr explicitly before the function returns.

Suggested change
pr, pw := io.Pipe()
pr, pw := io.Pipe()
defer pr.Close()

Copilot uses AI. Check for mistakes.

select {
case <-stop:
log.Println("Interrupted, stopping...")

Copilot AI Feb 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the program is interrupted via Ctrl+C (SIGINT/SIGTERM), there's no mechanism to stop the ongoing TTS generation in the goroutine. The goroutine will continue writing to the pipe writer (pw) even after interruption, which could lead to a panic if pw.Write is called after the pipe is closed or the player is closed. Consider using a context or closing the pipe writer to signal the callback to stop generating audio.

Suggested change
log.Println("Interrupted, stopping...")
log.Println("Interrupted, stopping...")
// Close the pipe writer to signal the TTS callback to stop generating audio.
_ = pw.Close()
// Wait for the TTS goroutine to finish cleanup.
<-done

Copilot uses AI. Check for mistakes.
This was referenced Feb 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants