cosyvoice

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 10 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

CosyVoice SDK for Golang

Go Reference Go Report Card codecov

This library provides unofficial Go clients for cosyvoice-websocket-api.

Installation

go get github.com/WqyJh/go-cosyvoice

Currently, go-cosyvoice requires Go version 1.19 or greater.

Usage

Async Synthesizer (Streaming)
import (
	"context"
	"fmt"
	"os"

	"github.com/WqyJh/go-cosyvoice"
)

func main() {
	client := cosyvoice.NewClient("your-api-key")

	ctx := context.Background()

	asyncSynthesizer, err := client.AsyncSynthesizer(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer asyncSynthesizer.Close()

    output, err := synthesizer.RunTask(ctx)
	if err != nil {
		log.Println("run task err", err)
		return
	}

    texts := []string{"Hello, world!", "你好,世界!"}
    for _, text := range texts {
		err := synthesizer.SendText(ctx, text)
		if err != nil {
			log.Println("send text err", err)
			return
		}
	}

	err = synthesizer.FinishTask(ctx)
	if err != nil {
		log.Println("finish task err", err)
		return
	}

    for result := range output {
        if result.Err != nil {
            log.Println("result err", result.Err)
            return
        }
        // handle audio data
        log.Println("received audio", len(result.Data))
    }
}
Sync Synthesizer (Non-Streaming)
import (
	"context"
	"fmt"
	"os"

	"github.com/WqyJh/go-cosyvoice"
)

func main() {
	client := cosyvoice.NewClient("your-api-key")

	ctx := context.Background()

	syncSynthesizer, err := client.SyncSynthesizer(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer syncSynthesizer.Close()

    output, err := syncSynthesizer.Call(ctx, "Hello, world!")
    if err != nil {
        log.Println("call err", err)
        return
    }

    for result := range output {
        if result.Err != nil {
            log.Println("result err", result.Err)
            return
        }
        // handle audio data
        log.Println("received audio", len(result.Data))
    }

    // another call
    output, err = syncSynthesizer.Call(ctx, "你好,世界!")
    if err != nil {
        log.Println("call err", err)
        return
    }
}
Use another WebSocket dialer

The default websocket library is coder/websocket. You can use another websocket library by setting a custom dialer.

import (
	gorilla "github.com/WqyJh/go-cosyvoice/contrib/ws-gorilla"
)


func main() {
	syncSynthesizer, err := client.SyncSynthesizer(ctx,
		cosyvoice.WithDialer(gorilla.NewWebSocketDialer(gorilla.WebSocketOptions{})),
	)
}

ADDATIONS

The conditions for WebSocket disconnection
  1. If task execution fails, the server sends the task-failed event and closes the websocketConnection.
  2. If the interval between two tasks exceeds 60 seconds, the connection will be disconnected due to timeout. In this package, after the Asynthesizer/Synthesizer object is created, a goroutine is started for health detection by send pingMessage. Developers don't need to worry about this condition.
  3. In task, if the interval between two commands exceeds 23S, the server triggers a timeout error and disconnects. When you use Asyncthesizer, if your business is likely to exceed 23S, periodically call SendText() to send empty characters or punctuation marks to prevent the connection breaking. Synthesizer is not needed.

Documentation

Index

Constants

View Source
const (
	FunctionSpeechSynthesizer string = "SpeechSynthesizer"
)
View Source
const (
	StreamingDuplex string = "duplex"
)
View Source
const (
	TaskGroupAudio string = "audio"
)
View Source
const (
	TaskTTS string = "tts"
)
View Source
const (
	TextTypePlainText string = "PlainText"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Action

type Action string
const (
	ActionRunTask      Action = "run-task"
	ActionContinueTask Action = "continue-task"
	ActionFinishTask   Action = "finish-task"
)

type AsyncSynthesizer

type AsyncSynthesizer struct {
	// contains filtered or unexported fields
}

func (*AsyncSynthesizer) Close

func (s *AsyncSynthesizer) Close() error

func (*AsyncSynthesizer) FinishTask

func (s *AsyncSynthesizer) FinishTask(ctx context.Context) error

func (*AsyncSynthesizer) RunTask

func (s *AsyncSynthesizer) RunTask(ctx context.Context) (<-chan Result, error)

func (*AsyncSynthesizer) SendText

func (s *AsyncSynthesizer) SendText(ctx context.Context, text string) error

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(apiKey string) *Client

func NewClientWithConfig

func NewClientWithConfig(config ClientConfig) *Client

func (*Client) AsyncSynthesizer

func (c *Client) AsyncSynthesizer(ctx context.Context, opts ...SynthesizerOption) (*AsyncSynthesizer, error)

func (*Client) SyncSynthesizer

func (c *Client) SyncSynthesizer(ctx context.Context, opts ...SynthesizerOption) (*SyncSynthesizer, error)

type ClientConfig

type ClientConfig struct {
	ApiKey string `json:"api_key"`
	WsUrl  string `json:"ws_url"`
}

func DefaultConfig

func DefaultConfig(apiKey string) ClientConfig

type Error

type Error struct {
	RequestID string `json:"request_id,omitempty"`
	Code      string `json:"error_code,omitempty"`
	Message   string `json:"error_message,omitempty"`
}

func (Error) Error

func (e Error) Error() string

type Event

type Event struct {
	Header  Header  `json:"header"`
	Payload Payload `json:"payload"`
}

type Format

type Format string
const (
	FormatPCM Format = "pcm"
	FormatWAV Format = "wav"
	FormatMP3 Format = "mp3"
)
type Header struct {
	Action     Action                 `json:"action"`
	TaskID     string                 `json:"task_id"`
	Streaming  string                 `json:"streaming"`
	Event      string                 `json:"event"`
	Attributes map[string]interface{} `json:"attributes"`
	Error
}

type Input

type Input struct {
	Text string `json:"text"`
}

type Model

type Model string
const (
	ModelCosyvoiceV1 Model = "cosyvoice-v1"
)

type Params

type Params struct {
	TextType   string     `json:"text_type"`        // PlainText
	Voice      Voice      `json:"voice"`            // longwan, longcheng, longhua, etc.
	Format     Format     `json:"format"`           // pcm, wav, mp3
	SampleRate SampleRate `json:"sample_rate"`      // 8000, 16000, 22050, 24000, 44100, 48000
	Volume     int        `json:"volume,omitempty"` // range: 0~100, default: 50
	Rate       int        `json:"rate,omitempty"`   // range: 0.5~2, default: 1.0
	Pitch      int        `json:"pitch,omitempty"`  // range: 0.5~2, default: 1.0
}

type Payload

type Payload struct {
	TaskGroup  string     `json:"task_group"`
	Task       string     `json:"task"`
	Function   string     `json:"function"`
	Model      Model      `json:"model"`
	Parameters Params     `json:"parameters"`
	Resources  []Resource `json:"resources"`
	Input      Input      `json:"input"`
}

type Resource

type Resource struct {
	ResourceID   string `json:"resource_id"`
	ResourceType string `json:"resource_type"`
}

type Result

type Result struct {
	Data []byte
	Err  error
}

type SampleRate

type SampleRate int
const (
	SampleRate8000  SampleRate = 8000
	SampleRate16000 SampleRate = 16000
	SampleRate22050 SampleRate = 22050
	SampleRate24000 SampleRate = 24000
	SampleRate44100 SampleRate = 44100
	SampleRate48000 SampleRate = 48000
)

type SyncSynthesizer

type SyncSynthesizer struct {
	// contains filtered or unexported fields
}

func (*SyncSynthesizer) Call

func (s *SyncSynthesizer) Call(ctx context.Context, text string) (<-chan Result, error)

func (*SyncSynthesizer) Close

func (s *SyncSynthesizer) Close() error

type SynthesizerConfig

type SynthesizerConfig struct {
	Model      Model      `json:"model"`            // cosyvoice-v1
	Voice      Voice      `json:"voice"`            // longwan, longcheng, longhua, etc.
	Format     Format     `json:"format"`           // pcm, wav, mp3
	SampleRate SampleRate `json:"sample_rate"`      // 8000, 16000, 22050, 24000, 44100, 48000
	Volume     int        `json:"volume,omitempty"` // range: 0~100, default: 50
	Rate       int        `json:"rate,omitempty"`   // range: 0.5~2, default: 1.0
	Pitch      int        `json:"pitch,omitempty"`  // range: 0.5~2, default: 1.0
}

func DefaultSynthesizerConfig

func DefaultSynthesizerConfig() SynthesizerConfig

type SynthesizerOption

type SynthesizerOption func(*synthesizerOption)

func WithChanSize

func WithChanSize(size int) SynthesizerOption

func WithDialer

func WithDialer(dialer openairt.WebSocketDialer) SynthesizerOption

func WithLogger

func WithLogger(logger openairt.Logger) SynthesizerOption

func WithPingInterval

func WithPingInterval(interval int) SynthesizerOption

func WithSynthesizerConfig

func WithSynthesizerConfig(config SynthesizerConfig) SynthesizerOption

type Task

type Task struct {
	// contains filtered or unexported fields
}

type Voice

type Voice string
const (
	Longwan       Voice = "longwan"
	Longcheng     Voice = "longcheng"
	Longhua       Voice = "longhua"
	Longxiaochun  Voice = "longxiaochun"
	Longxiaoxia   Voice = "longxiaoxia"
	Longxiaocheng Voice = "longxiaocheng"
	Longxiaobai   Voice = "longxiaobai"
	Longlaotie    Voice = "longlaotie"
	Longshu       Voice = "longshu"
	Longjing      Voice = "longjing"
	Longmiao      Voice = "longmiao"
	Longyue       Voice = "longyue"
	Longyuan      Voice = "longyuan"
	Longfei       Voice = "longfei"
	Longjielidou  Voice = "longjielidou"
	Longshuo      Voice = "longshuo"
	Longtong      Voice = "longtong"
	Longxiang     Voice = "longxiang"
	Loongstella   Voice = "loongstella"
	Loongbella    Voice = "loongbella"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址