voicekit

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 18 Imported by: 0

README

VoiceKit — Go SDK

Go Reference CI

Official Go wrapper for VoiceKit — the REST API for Russian speech: neural speech synthesis (TTS), transcription (STT) with diarization and timestamps, sentiment analysis, voice cloning, voice biometrics, audio/video effects, call QA, semantic search over recordings and batch operations.

Links: Website · Documentation · API reference · Pricing · Blog

One dependency (github.com/coder/websocket, used only by the streaming client); everything else is the standard library. Requires Go 1.22+.

Install

go get github.com/lomshakov/voicekit-go

Quick start

package main

import (
	"context"
	"log"
	"os"
	"time"

	"github.com/lomshakov/voicekit-go"
)

func main() {
	client, err := voicekit.NewClient("rtt_…")
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	// Synthesis → raw audio bytes
	audio, err := client.Synthesize(ctx, "Привет! Это синтез русской речи.", &voicekit.SynthesizeOptions{
		Voice:  "preset_anna",
		Format: "mp3",
	})
	if err != nil {
		log.Fatal(err)
	}
	if err := os.WriteFile("speech.mp3", audio, 0o644); err != nil {
		log.Fatal(err)
	}

	// Transcription (async → poll)
	job, err := client.Transcribe(ctx, voicekit.Bytes(audio), &voicekit.TranscribeOptions{
		Language: "ru",
		Keyterms: []string{"диагноз", "препарат"},
	})
	if err != nil {
		log.Fatal(err)
	}
	for {
		result, err := client.GetTranscriptionJob(ctx, job.Str("job_id"))
		if err != nil {
			log.Fatal(err)
		}
		status := result.Str("status")
		if status == "completed" || status == "failed" {
			log.Println(status, result.Str("text"))
			break
		}
		time.Sleep(time.Second)
	}
}
Configuration
client, err := voicekit.NewClient(os.Getenv("VOICEKIT_API_KEY"),
	voicekit.WithBaseURL("https://ttsapi.ru"), // default
	voicekit.WithTimeout(2*time.Minute),       // default 120s
	voicekit.WithHTTPClient(myHTTPClient),     // custom transport / proxy
)
Error handling

Every non-2xx response becomes an *voicekit.APIError carrying the RFC 7807 code:

_, err := client.SynthesizeStream(ctx, text, nil)
switch {
case errors.Is(err, voicekit.ErrForbidden):
	log.Println("upgrade your plan:", voicekit.ErrorCode(err)) // streaming_forbidden
case voicekit.IsCode(err, "quota_exceeded"):
	log.Println("monthly quota is over")
case errors.Is(err, voicekit.ErrRateLimited):
	log.Println("slow down")
default:
	log.Println(err)
}

Features

Area Methods
Synthesis Synthesize, SynthesizeStream, SynthesizeAsync, GetSynthesisJob, DownloadSynthesisAudio
Voices Voices, Voice, CreateCloneVoice, ListCloneVoices, GetCloneVoice, DeleteCloneVoice
Transcription Transcribe, TranscribeSync, GetTranscriptionJob, Subtitles, TranslateTranscript, VAD
Analysis Analyze, AnalyzeSync, GetAnalysisJob, DetectLanguage, Redact, Topics, Summarize, Moderate, Evaluate
Effects ApplyAudioEffects, ApplyVideoEffects, CleanAudio + job/status/download helpers
Voice ID AnalyzeVoice, EnrollVoice, VerifyVoice, IdentifyVoice, ListVoiceProfiles, DeleteVoiceProfile
Recordings ListRecordings, GetRecording, RecordingTranscript, RecordingSpeakers, UpdateRecording, UpdateSpeaker, RecordingFromLink, ExportRecording, DownloadRecordingAudio, share links
Call QA QAEvaluate, QAAnalytics, QAEvaluations, QAExport
Search Search, Ask, MeetingProtocol
Batch / account BatchSynthesize, BatchAnalyze, GetBatch, Usage, BillingBalance
Streaming TranscribeStream, VADStream (WebSocket, Pro/Business)
Streaming synthesis (Pro/Business)
rc, err := client.SynthesizeStream(ctx, "Первое предложение. Второе предложение.", nil)
if err != nil {
	return err
}
defer rc.Close()

out, err := os.Create("long.mp3")
if err != nil {
	return err
}
defer out.Close()
_, err = io.Copy(out, rc) // chunks arrive as the engine produces them
Audio effects (Free/Basic/Pro/Business)
chain, err := voicekit.EffectsJSON([]map[string]any{
	{"type": "reverb", "room_size": 0.5},
	{"type": "pitch", "semitones": 2},
})
if err != nil {
	return err
}

// Inline during synthesis
audio, err := client.Synthesize(ctx, "Привет!", &voicekit.SynthesizeOptions{
	Voice:   "preset_anna",
	Effects: chain,
})

// Or as a background job over an existing file
job, err := client.ApplyAudioEffects(ctx, voicekit.Bytes(audio), &voicekit.AudioEffectsOptions{
	Effects:      []map[string]any{{"type": "compressor", "ratio": 3}},
	OutputFormat: "mp3",
})
Audio cleaning (Free/Basic/Pro/Business)
job, err := client.CleanAudio(ctx, voicekit.Bytes(noisy), nil) // one-click: denoise + normalize
// job, err = client.CleanAudio(ctx, voicekit.Bytes(noisy), &voicekit.CleanAudioOptions{
//	Options: map[string]any{"denoise": map[string]any{"strength": 0.8}, "high_pass": 80},
// })
result, err := client.GetAudioCleaningJob(ctx, job.Str("job_id"))
clean, err := client.DownloadAudioCleaning(ctx, job.Str("job_id"))
Voice ID (Pro/Business)
// Voice passport: language, gender, age, emotion, speaker embedding, AI-vs-human
passport, err := client.AnalyzeVoice(ctx, voicekit.Bytes(sample))

// Voice biometrics over your own profiles
profile, err := client.EnrollVoice(ctx, voicekit.Bytes(speaker), "Alice")
check, err := client.VerifyVoice(ctx, voicekit.Bytes(other), profile.Str("profile_id"))
match, err := client.IdentifyVoice(ctx, voicekit.Bytes(other), nil) // 1:N
Recordings, QA & meeting intelligence (Pro/Business)
recordings, err := client.ListRecordings(ctx, &voicekit.RecordingListOptions{Limit: 10})
job, err := client.RecordingFromLink(ctx, "https://example.com/call.mp3", "ru")
speakers, err := client.RecordingSpeakers(ctx, recordingID)
_, err = client.UpdateSpeaker(ctx, recordingID, "SPEAKER_00", "Иван", "operator")

folder := "Q3"
_, err = client.UpdateRecording(ctx, recordingID, voicekit.UpdateRecordingOptions{
	Tags:   []string{"sales", "warm"},
	Folder: &folder,
})
pdf, err := client.ExportRecording(ctx, recordingID, "pdf")

qa, err := client.QAEvaluate(ctx, recordingID, &voicekit.QAEvaluateOptions{
	Checklist: []map[string]any{{"id": "greeting", "kind": "required", "description": "Поздоровался"}},
})
trend, err := client.QAAnalytics(ctx, 30)

hits, err := client.Search(ctx, "почему клиент отказался?", &voicekit.SearchOptions{Limit: 5, Keywords: "дорого"})
answer, err := client.Ask(ctx, "почему клиент отказался от Pro?")
protocol, err := client.MeetingProtocol(ctx, recordingID, "standup")
WebSocket streaming (Pro/Business)
stream, err := client.TranscribeStream(ctx, &voicekit.StreamOptions{Language: "ru"})
if err != nil {
	return err
}
defer stream.Close()

if err := stream.SendAudio(ctx, pcm16Chunk); err != nil { // raw PCM16, 16 kHz mono
	return err
}
if err := stream.Stop(ctx); err != nil { // finalize the utterance
	return err
}
for {
	event, err := stream.Receive(ctx)
	if errors.Is(err, voicekit.ErrStreamClosed) {
		break
	}
	if err != nil {
		return err
	}
	fmt.Println(event.Str("type"), event.Str("text")) // session / vad / partial / final / error
}
Batches
batch, err := client.BatchSynthesize(ctx, []map[string]any{
	{"text": "Первый текст", "voice": "preset_anna"},
	{"text": "Второй текст", "voice": "preset_dmitri"},
})
status, err := client.GetBatch(ctx, batch.Str("batch_id"))

// Analysis batches take inline base64 audio
audio, err := voicekit.B64File("call.wav")
batch, err = client.BatchAnalyze(ctx, []map[string]any{{"audio": audio, "language": "ru"}})

Dynamic responses

The API evolves, so the SDK returns voicekit.Object (map[string]any) with typed accessors instead of freezing every field into a struct:

result, err := client.GetTranscriptionJob(ctx, jobID)
text := result.Str("text")
seconds := result.Num("duration_seconds")
segments := result.List("segments")
for _, segment := range segments {
	fmt.Println(segment.Num("start"), segment.Str("text"))
}

Development

go vet ./...
go test -race ./...

License

MIT © VoiceKit

Documentation

Overview

Package voicekit is the official Go SDK for the VoiceKit API — Russian text-to-speech, speech-to-text with diarization, voice cloning, voice biometrics, audio/video effects, call QA, semantic search and batch jobs.

client, err := voicekit.NewClient("YOUR_KEY")
if err != nil {
	log.Fatal(err)
}
audio, err := client.Synthesize(ctx, "Привет! Это синтез русской речи.", &voicekit.SynthesizeOptions{
	Voice:  "preset_anna",
	Format: "mp3",
})
if err != nil {
	log.Fatal(err)
}
os.WriteFile("speech.mp3", audio, 0o644)

A Client is safe for concurrent use by multiple goroutines; create one and reuse it. Every call takes a context.Context and honours its deadline.

Index

Constants

View Source
const (
	// DefaultBaseURL is the public VoiceKit endpoint.
	DefaultBaseURL = "https://ttsapi.ru"

	// Version is the SDK release version.
	Version = "0.4.0"
)

Variables

View Source
var (
	// ErrUnauthorized is a 401 response (missing or invalid API key).
	ErrUnauthorized = &APIError{Status: http.StatusUnauthorized}
	// ErrForbidden is a 403 response (plan does not include the feature).
	ErrForbidden = &APIError{Status: http.StatusForbidden}
	// ErrNotFound is a 404 response.
	ErrNotFound = &APIError{Status: http.StatusNotFound}
	// ErrRateLimited is a 429 response.
	ErrRateLimited = &APIError{Status: http.StatusTooManyRequests}
)

Sentinel errors for the most common statuses; combine with errors.Is:

if errors.Is(err, voicekit.ErrUnauthorized) { … }
View Source
var ErrStreamClosed = errors.New("voicekit: stream closed")

ErrStreamClosed is returned by Stream.Receive once the server closes the session.

Functions

func B64

func B64(data []byte) string

B64 encodes audio bytes as base64 for inline batch items.

func B64File

func B64File(path string) (string, error)

B64File reads a file and encodes it as base64 for inline batch items.

func EffectsJSON

func EffectsJSON(effects []map[string]any) (string, error)

EffectsJSON encodes an effect chain into the JSON string the API expects.

func ErrorCode

func ErrorCode(err error) string

ErrorCode returns the machine-readable code carried by err, or "".

func IsCode

func IsCode(err error, code string) bool

IsCode reports whether err is an APIError with the given error code.

func StatusCode

func StatusCode(err error) int

StatusCode returns the HTTP status carried by err, or 0 when err is not an APIError.

Types

type APIError

type APIError struct {
	// Status is the HTTP status code.
	Status int
	// Code is the stable error code from the response body ("" when absent).
	Code string
	// Message is the human-readable detail (or title).
	Message string
}

APIError is returned when the API answers with a non-2xx status. The payload follows RFC 7807 Problem Details, so Code is the machine-readable error code (e.g. "quota_exceeded", "streaming_forbidden").

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is matches sentinel errors by status: a sentinel without a Code matches any error carrying the same HTTP status.

type AnalyzeOptions

type AnalyzeOptions struct {
	Language    string
	Diarization bool
	Keyterms    []string
	Clean       bool
	WebhookURL  string
}

AnalyzeOptions controls POST /v1/analyze (async job).

type AnalyzeSyncOptions

type AnalyzeSyncOptions struct {
	Language    string
	Diarization bool
	// Emotions, Keywords and Entities default to true server-side; set the
	// pointers to disable an individual extractor.
	Emotions *bool
	Keywords *bool
	Entities *bool
	Keyterms []string
	Clean    bool
}

AnalyzeSyncOptions controls POST /v1/analyze/sync (files up to 3 min).

type Attachment

type Attachment struct {
	// Name is the file name reported to the server (e.g. "audio.wav").
	Name string
	// ContentType is the MIME type (e.g. "audio/wav").
	ContentType string
	// Data holds the raw file bytes.
	Data []byte
}

Attachment is a file uploaded with a multipart/form-data request.

func Bytes

func Bytes(data []byte) Attachment

Bytes builds an Attachment from raw bytes (name "audio.wav").

func File

func File(path string) (Attachment, error)

File reads a file from disk into an Attachment, guessing the MIME type from the extension.

func (Attachment) WithContentType

func (a Attachment) WithContentType(contentType string) Attachment

WithContentType overrides the MIME type of an attachment.

func (Attachment) WithName

func (a Attachment) WithName(name string) Attachment

WithName overrides the file name of an attachment.

type AudioEffectsOptions

type AudioEffectsOptions struct {
	// Effects is the effect chain, e.g. {[]map[string]any{{"type": "reverb", "room_size": 0.5}}}
	Effects []map[string]any
	// OutputFormat is "wav" (default), "mp3" or "ogg".
	OutputFormat string
	// WebhookURL receives the result when the job completes.
	WebhookURL string
}

AudioEffectsOptions controls POST /v1/audio/effects.

type CleanAudioOptions

type CleanAudioOptions struct {
	// Options is the cleaning preset; nil applies denoise + normalize.
	//
	//	{"denoise": {"strength": 0.8, "stationary": true},
	//	 "normalize": {"target_db": -1.0}, "high_pass": 80, "low_pass": 12000}
	Options map[string]any
	// OutputFormat is "wav" (default), "mp3" or "ogg".
	OutputFormat string
	WebhookURL   string
}

CleanAudioOptions controls POST /v1/audio/clean.

type Client

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

Client is a typed wrapper over the VoiceKit REST API.

func NewClient

func NewClient(apiKey string, opts ...Option) (*Client, error)

NewClient creates a client for the given API key. The key is required.

func (*Client) Analyze

func (c *Client) Analyze(ctx context.Context, audio Attachment, opts *AnalyzeOptions) (Object, error)

Analyze starts an async analysis job (emotions, keywords, entities, optionally per speaker); poll it with GetAnalysisJob.

func (*Client) AnalyzeSync

func (c *Client) AnalyzeSync(ctx context.Context, audio Attachment, opts *AnalyzeSyncOptions) (Object, error)

AnalyzeSync analyses a short file synchronously.

func (*Client) AnalyzeVoice

func (c *Client) AnalyzeVoice(ctx context.Context, audio Attachment) (Object, error)

AnalyzeVoice returns a voice passport: language, gender, age group, emotional background, a speaker embedding and an AI-vs-human probability (ai_probability is null when anti-spoofing is not configured).

func (*Client) ApplyAudioEffects

func (c *Client) ApplyAudioEffects(ctx context.Context, audio Attachment, opts *AudioEffectsOptions) (Object, error)

ApplyAudioEffects starts an async audio-effects job; poll it with GetAudioEffectsJob and fetch the result with DownloadAudioEffects.

func (*Client) ApplyVideoEffects

func (c *Client) ApplyVideoEffects(ctx context.Context, video Attachment, opts *VideoEffectsOptions) (Object, error)

ApplyVideoEffects starts an async video-effects job; poll it with GetVideoEffectsJob and fetch the artifact with DownloadVideoEffects.

func (*Client) Ask

func (c *Client) Ask(ctx context.Context, query string) (Object, error)

Ask answers a question over the recording library (RAG) with verbatim citations.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the configured API endpoint.

func (*Client) BatchAnalyze

func (c *Client) BatchAnalyze(ctx context.Context, items []map[string]any) (Object, error)

BatchAnalyze queues a batch of analysis requests; each item needs an inline base64 "audio" field (see B64 and B64File).

func (*Client) BatchSynthesize

func (c *Client) BatchSynthesize(ctx context.Context, items []map[string]any) (Object, error)

BatchSynthesize queues a batch of synthesis requests; each item is a /v1/synthesize body. Poll the batch with GetBatch.

func (*Client) BillingBalance

func (c *Client) BillingBalance(ctx context.Context) (Object, error)

BillingBalance returns the current balance, plan and recent transactions.

func (*Client) CleanAudio

func (c *Client) CleanAudio(ctx context.Context, audio Attachment, opts *CleanAudioOptions) (Object, error)

CleanAudio starts an async audio-cleaning job; poll it with GetAudioCleaningJob and fetch the result with DownloadAudioCleaning.

func (*Client) CreateCloneVoice

func (c *Client) CreateCloneVoice(ctx context.Context, name, promptText string, samples []Attachment, language string) (Object, error)

CreateCloneVoice creates a cloned voice from reference audio (Pro/Business). promptText must be the exact transcript of the reference clip; samples may contain one or more reference files.

func (*Client) CreateShare

func (c *Client) CreateShare(ctx context.Context, recordingID string, opts *CreateShareOptions) (Object, error)

CreateShare creates a public share link for a recording.

func (*Client) DeleteCloneVoice

func (c *Client) DeleteCloneVoice(ctx context.Context, cloneID string) error

DeleteCloneVoice deletes a cloned voice and its reference latents.

func (*Client) DeleteRecording

func (c *Client) DeleteRecording(ctx context.Context, recordingID string) error

DeleteRecording deletes a recording and its stored audio.

func (*Client) DeleteVoiceProfile

func (c *Client) DeleteVoiceProfile(ctx context.Context, profileID string) error

DeleteVoiceProfile deletes an enrolled voice profile by id.

func (*Client) DetectLanguage

func (c *Client) DetectLanguage(ctx context.Context, text string) (Object, error)

DetectLanguage identifies the language of a raw text.

func (*Client) DownloadAudioCleaning

func (c *Client) DownloadAudioCleaning(ctx context.Context, jobID string) ([]byte, error)

DownloadAudioCleaning downloads the cleaned audio of a completed job.

func (*Client) DownloadAudioEffects

func (c *Client) DownloadAudioEffects(ctx context.Context, jobID string) ([]byte, error)

DownloadAudioEffects downloads the processed audio of a completed job.

func (*Client) DownloadRecordingAudio

func (c *Client) DownloadRecordingAudio(ctx context.Context, recordingID string) ([]byte, error)

DownloadRecordingAudio downloads a recording's stored audio.

func (*Client) DownloadSynthesisAudio

func (c *Client) DownloadSynthesisAudio(ctx context.Context, jobID string) ([]byte, error)

DownloadSynthesisAudio downloads the produced WAV of a completed job.

func (*Client) DownloadVideoEffects

func (c *Client) DownloadVideoEffects(ctx context.Context, jobID string) ([]byte, error)

DownloadVideoEffects downloads the produced artifact (video or audio).

func (*Client) EnrollVoice

func (c *Client) EnrollVoice(ctx context.Context, audio Attachment, name string) (Object, error)

EnrollVoice stores an audio clip as a reusable voice profile; the response carries profile_id.

func (*Client) Evaluate

func (c *Client) Evaluate(ctx context.Context, audio Attachment, reference string, opts *EvaluateOptions) (Object, error)

Evaluate measures speech quality (word error rate) against a reference text.

func (*Client) ExportRecording

func (c *Client) ExportRecording(ctx context.Context, recordingID, format string) ([]byte, error)

ExportRecording exports a transcript as txt, md, srt, vtt, docx or pdf.

func (*Client) GetAnalysisJob

func (c *Client) GetAnalysisJob(ctx context.Context, jobID string) (Object, error)

GetAnalysisJob polls an analysis job.

func (*Client) GetAudioCleaningJob

func (c *Client) GetAudioCleaningJob(ctx context.Context, jobID string) (Object, error)

GetAudioCleaningJob polls an audio-cleaning job.

func (*Client) GetAudioEffectsJob

func (c *Client) GetAudioEffectsJob(ctx context.Context, jobID string) (Object, error)

GetAudioEffectsJob polls an audio-effects job.

func (*Client) GetBatch

func (c *Client) GetBatch(ctx context.Context, batchID string) (Object, error)

GetBatch polls a batch job.

func (*Client) GetCloneVoice

func (c *Client) GetCloneVoice(ctx context.Context, cloneID string) (Object, error)

GetCloneVoice returns one cloned voice by id.

func (*Client) GetRecording

func (c *Client) GetRecording(ctx context.Context, recordingID string) (Object, error)

GetRecording returns a recording's metadata.

func (*Client) GetSynthesisJob

func (c *Client) GetSynthesisJob(ctx context.Context, jobID string) (Object, error)

GetSynthesisJob polls a long-form synthesis job and returns its manifest.

func (*Client) GetTranscriptionJob

func (c *Client) GetTranscriptionJob(ctx context.Context, jobID string) (Object, error)

GetTranscriptionJob polls a transcription job.

func (*Client) GetVideoEffectsJob

func (c *Client) GetVideoEffectsJob(ctx context.Context, jobID string) (Object, error)

GetVideoEffectsJob polls a video-effects job.

func (*Client) IdentifyVoice

func (c *Client) IdentifyVoice(ctx context.Context, audio Attachment, profileIDs []string) (Object, error)

IdentifyVoice finds the closest matching profile (1:N). Pass nil profileIDs to search every profile of the caller.

func (*Client) ListCloneVoices

func (c *Client) ListCloneVoices(ctx context.Context) ([]Object, error)

ListCloneVoices lists the caller's cloned voices.

func (*Client) ListRecordings

func (c *Client) ListRecordings(ctx context.Context, opts *RecordingListOptions) (Object, error)

ListRecordings lists the caller's recordings (newest first).

func (*Client) ListShares

func (c *Client) ListShares(ctx context.Context, recordingID string) ([]Object, error)

ListShares lists the active share links of a recording.

func (*Client) ListVoiceProfiles

func (c *Client) ListVoiceProfiles(ctx context.Context) ([]Object, error)

ListVoiceProfiles lists the caller's enrolled voice profiles.

func (*Client) MeetingProtocol

func (c *Client) MeetingProtocol(ctx context.Context, recordingID, template string) (Object, error)

MeetingProtocol generates a meeting protocol from a recording transcript. Template is one of custom, standup, demo, interview, retro, one_on_one.

func (*Client) Moderate

func (c *Client) Moderate(ctx context.Context, text, language string) (Object, error)

Moderate flags profanity, insults and hate speech in raw text.

func (*Client) QAAnalytics

func (c *Client) QAAnalytics(ctx context.Context, days int) (Object, error)

QAAnalytics returns the score trend, top violations and score by operator.

func (*Client) QAEvaluate

func (c *Client) QAEvaluate(ctx context.Context, recordingID string, opts *QAEvaluateOptions) (Object, error)

QAEvaluate scores a recording against a QA checklist (Pro/Business).

func (*Client) QAEvaluations

func (c *Client) QAEvaluations(ctx context.Context, limit, offset int) (Object, error)

QAEvaluations lists persisted QA evaluations (newest first).

func (*Client) QAExport

func (c *Client) QAExport(ctx context.Context, format string, days int) ([]byte, error)

QAExport exports QA evaluations as CSV or JSON for CRM import.

func (*Client) RecordingFolders

func (c *Client) RecordingFolders(ctx context.Context) ([]string, error)

RecordingFolders returns the distinct folders across the caller's recordings.

func (c *Client) RecordingFromLink(ctx context.Context, audioURL, language string) (Object, error)

RecordingFromLink starts a diarized transcription from a public audio URL; the recording is tagged with source "link".

func (*Client) RecordingSpeakers

func (c *Client) RecordingSpeakers(ctx context.Context, recordingID string) (Object, error)

RecordingSpeakers returns a recording's speakers, timeline and metrics.

func (*Client) RecordingTags

func (c *Client) RecordingTags(ctx context.Context) ([]string, error)

RecordingTags returns the distinct tags across the caller's recordings.

func (*Client) RecordingTranscript

func (c *Client) RecordingTranscript(ctx context.Context, recordingID string) (Object, error)

RecordingTranscript returns a recording's transcript.

func (*Client) Redact

func (c *Client) Redact(ctx context.Context, text, language string) (Object, error)

Redact masks PII (names, phones, addresses, card numbers) in raw text.

func (*Client) RevokeShare

func (c *Client) RevokeShare(ctx context.Context, recordingID, token string) error

RevokeShare revokes a share link.

func (*Client) Search

func (c *Client) Search(ctx context.Context, query string, opts *SearchOptions) (Object, error)

Search runs a hybrid semantic/full-text search over recordings (Pro/Business).

func (*Client) Subtitles

func (c *Client) Subtitles(ctx context.Context, jobID string, opts *SubtitleOptions) (string, error)

Subtitles downloads VTT/SRT captions for a completed transcription job.

func (*Client) Summarize

func (c *Client) Summarize(ctx context.Context, text string, opts *SummarizeOptions) (Object, error)

Summarize condenses raw text into a short summary.

func (*Client) Synthesize

func (c *Client) Synthesize(ctx context.Context, text string, opts *SynthesizeOptions) ([]byte, error)

Synthesize converts text to speech and returns the raw audio bytes.

func (*Client) SynthesizeAsync

func (c *Client) SynthesizeAsync(ctx context.Context, text string, opts *SynthesizeAsyncOptions) (Object, error)

SynthesizeAsync queues a long-form synthesis job. Poll it with GetSynthesisJob and fetch the audio with DownloadSynthesisAudio.

func (*Client) SynthesizeStream

func (c *Client) SynthesizeStream(ctx context.Context, text string, opts *SynthesizeOptions) (io.ReadCloser, error)

SynthesizeStream starts a streaming synthesis (Pro/Business) and returns the response body. Audio chunks arrive as the engine produces them; the caller must close the reader.

rc, err := client.SynthesizeStream(ctx, longText, nil)
if err != nil { return err }
defer rc.Close()
_, err = io.Copy(out, rc)

func (*Client) Topics

func (c *Client) Topics(ctx context.Context, text, language string) (Object, error)

Topics extracts key topics from raw text.

func (*Client) Transcribe

func (c *Client) Transcribe(ctx context.Context, audio Attachment, opts *TranscribeOptions) (Object, error)

Transcribe starts an async transcription job; poll it with GetTranscriptionJob.

func (*Client) TranscribeStream

func (c *Client) TranscribeStream(ctx context.Context, opts *StreamOptions) (*Stream, error)

TranscribeStream opens WS /v1/transcribe/stream (Pro/Business).

func (*Client) TranscribeSync

func (c *Client) TranscribeSync(ctx context.Context, audio Attachment, opts *TranscribeSyncOptions) (Object, error)

TranscribeSync transcribes a short file synchronously.

func (*Client) TranslateTranscript

func (c *Client) TranslateTranscript(ctx context.Context, jobID, targetLanguage string) (Object, error)

TranslateTranscript translates a completed transcript, preserving timestamps and speakers. Billed against the plan's LLM token budget.

func (*Client) UpdateRecording

func (c *Client) UpdateRecording(ctx context.Context, recordingID string, opts UpdateRecordingOptions) (Object, error)

UpdateRecording updates a recording's tags and/or folder.

func (*Client) UpdateSpeaker

func (c *Client) UpdateSpeaker(ctx context.Context, recordingID, speakerID, displayName, role string) (Object, error)

UpdateSpeaker renames a diarized speaker or assigns a role (operator, client, participant).

func (*Client) Usage

func (c *Client) Usage(ctx context.Context) (Object, error)

Usage returns the current monthly usage for the authenticated key.

func (*Client) VAD

func (c *Client) VAD(ctx context.Context, audio Attachment) (Object, error)

VAD detects speech segments in an audio file (Silero VAD).

func (*Client) VADStream

func (c *Client) VADStream(ctx context.Context) (*Stream, error)

VADStream opens WS /v1/vad/stream for speech turn detection without recognition.

func (*Client) VerifyVoice

func (c *Client) VerifyVoice(ctx context.Context, audio Attachment, profileID string) (Object, error)

VerifyVoice compares a clip against an enrolled profile (1:1) and returns profile_id, similarity, verified and threshold.

func (*Client) Voice

func (c *Client) Voice(ctx context.Context, voiceID string) (Object, error)

Voice returns one voice by id (e.g. "preset_anna").

func (*Client) Voices

func (c *Client) Voices(ctx context.Context) ([]Object, error)

Voices returns the voice catalog.

type CreateShareOptions

type CreateShareOptions struct {
	// ExpiresInSeconds limits the link lifetime (0 = no expiry).
	ExpiresInSeconds int
	// Password protects the link.
	Password string
}

CreateShareOptions controls POST /v1/recordings/{id}/share.

type EvaluateOptions

type EvaluateOptions struct {
	Language string
	// Normalize ignores case and punctuation; nil = server default.
	Normalize *bool
}

EvaluateOptions controls POST /v1/eval.

type Object

type Object map[string]any

Object is a decoded JSON object returned by the API. Response shapes evolve server-side, so the SDK hands back dynamic objects with typed accessors instead of freezing every field into a struct.

func (Object) Bool

func (o Object) Bool(key string) bool

Bool returns the boolean value at key (false when absent or not a bool).

func (Object) Get

func (o Object) Get(key string) any

Get returns the raw value at key (nil when absent).

func (Object) Int

func (o Object) Int(key string) int

Int returns the integer value at key (0 when absent).

func (Object) List

func (o Object) List(key string) []Object

List returns the nested array at key as objects.

func (Object) Num

func (o Object) Num(key string) float64

Num returns the numeric value at key (0 when absent or not a number).

func (Object) Obj

func (o Object) Obj(key string) Object

Obj returns the nested object at key (nil when absent).

func (Object) Str

func (o Object) Str(key string) string

Str returns the string value at key ("" when absent or not a string).

func (Object) Strings

func (o Object) Strings(key string) []string

Strings returns the nested array at key as strings.

type Option

type Option func(*config)

Option customises a Client created by NewClient.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL overrides the API endpoint (default DefaultBaseURL).

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient injects a custom *http.Client. The client's own Timeout wins over WithTimeout.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout (default 120s).

type QAEvaluateOptions

type QAEvaluateOptions struct {
	// Checklist holds items such as
	// {"id": "greeting", "kind": "required", "description": "...", "weight": 1.0}.
	Checklist []map[string]any
	// WebhookURL receives a qa.violation event when the call is flagged.
	WebhookURL string
}

QAEvaluateOptions controls POST /v1/qa/evaluate.

type RecordingListOptions

type RecordingListOptions struct {
	// Source is one of upload, link, bot, stream.
	Source string
	Tag    string
	Folder string
	Limit  int
	Offset int
}

RecordingListOptions filters GET /v1/recordings.

type SearchOptions

type SearchOptions struct {
	Limit int
	// Keywords enables full-text ranking on top of semantic similarity.
	Keywords string
	// Source is one of upload, link, bot, stream.
	Source string
	// Speaker is a diarization label such as SPEAKER_00.
	Speaker string
	// From and To are ISO-8601 timestamps (UTC).
	From string
	To   string
	// MinDuration and MaxDuration bound the recording length in seconds.
	MinDuration float64
	MaxDuration float64
}

SearchOptions filters POST /v1/search.

type Stream

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

Stream is a bidirectional VoiceKit WebSocket session. It carries raw PCM16 (16 kHz, mono, little-endian) binary frames up and JSON events (session, vad, partial, final, error) down. It is not safe for concurrent use; call Send and Receive from the same goroutine or guard them yourself.

func (*Stream) Close

func (s *Stream) Close() error

Close closes the WebSocket with a normal-closure status.

func (*Stream) Receive

func (s *Stream) Receive(ctx context.Context) (Object, error)

Receive reads the next JSON event. It returns ErrStreamClosed after a normal server-side close.

func (*Stream) SendAudio

func (s *Stream) SendAudio(ctx context.Context, pcm16 []byte) error

SendAudio writes a raw PCM16 frame (16 kHz, mono, little-endian).

func (*Stream) SendJSON

func (s *Stream) SendJSON(ctx context.Context, message any) error

SendJSON writes a control message; maps and structs are JSON-encoded.

func (*Stream) Stop

func (s *Stream) Stop(ctx context.Context) error

Stop signals the end of speech so the server finalizes the utterance.

type StreamOptions

type StreamOptions struct {
	// Language is an ISO-639-1 hint; empty = auto-detect.
	Language string
	// Keyterms biases recognition towards domain vocabulary.
	Keyterms []string
	// Interim enables interim results (server default is true).
	Interim *bool
}

StreamOptions controls a streaming transcription session.

type SubtitleOptions

type SubtitleOptions struct {
	// Format is "vtt" (default) or "srt".
	Format string
	// TargetLanguage translates the captions (e.g. "en").
	TargetLanguage string
	// HotMarks marks fast or unclear speech.
	HotMarks bool
}

SubtitleOptions controls GET /v1/transcribe/{id}/subtitles.

type SummarizeOptions

type SummarizeOptions struct {
	Language string
	// MaxSentences caps the summary length (0 = server default).
	MaxSentences int
}

SummarizeOptions controls POST /v1/analyze/summarize.

type SynthesizeAsyncOptions

type SynthesizeAsyncOptions struct {
	Voice      string
	Format     string
	SampleRate int
	Speed      float64
	Model      string
	Language   string
	WebhookURL string
}

SynthesizeAsyncOptions controls POST /v1/synthesize/async (long-form audiobook jobs). Long-form synthesis always returns WAV.

type SynthesizeOptions

type SynthesizeOptions struct {
	// Voice is a preset id (e.g. "preset_anna") or a cloned voice id.
	Voice string
	// Format is mp3 (default), wav or ogg.
	Format string
	// SampleRate is the output sample rate in Hz.
	SampleRate int
	// Speed is a multiplier, 1.0 = normal.
	Speed float64
	// Pitch shifts the voice in semitones.
	Pitch float64
	// Emotion selects a preset emotion on supported voices.
	Emotion string
	// SSML switches the input to SSML markup.
	SSML *bool
	// PutAccent and PutYo are accepted for compatibility and do not affect
	// synthesis (the engine reads stress and "ё" on its own).
	PutAccent *bool
	PutYo     *bool
	// Normalize applies loudness normalisation to the result.
	Normalize *bool
	// Model is "standard" (default) or "premium" (clone, Pro/Business).
	Model string
	// Language overrides the synthesis language for clones.
	Language string
	// Effects is a JSON array of effect descriptors, see EffectsJSON.
	Effects string
}

SynthesizeOptions controls POST /v1/synthesize and /v1/synthesize/stream.

type TranscribeOptions

type TranscribeOptions struct {
	// Language is an ISO-639-1 hint; empty = auto-detect.
	Language string
	// Diarization labels speakers (Basic and above).
	Diarization bool
	// Keyterms biases recognition towards domain vocabulary.
	Keyterms []string
	// Clean runs denoise + normalize before recognition.
	Clean bool
	// LongForm enables long-form transcription (up to 4 h / 512 MB).
	LongForm bool
	// WebhookURL receives the result when the job completes.
	WebhookURL string
}

TranscribeOptions controls POST /v1/transcribe (async job).

type TranscribeSyncOptions

type TranscribeSyncOptions struct {
	Language    string
	Diarization bool
	Keyterms    []string
	Clean       bool
}

TranscribeSyncOptions controls POST /v1/transcribe/sync (files up to 3 min).

type UpdateRecordingOptions

type UpdateRecordingOptions struct {
	// Tags replaces the tag set; nil leaves it untouched.
	Tags []string
	// ClearTags removes every tag (wins over Tags).
	ClearTags bool
	// Folder moves the recording; nil leaves it untouched, a pointer to ""
	// clears the folder.
	Folder *string
}

UpdateRecordingOptions patches a recording's tags and folder. Zero-valued fields are left untouched server-side.

type VideoEffectsOptions

type VideoEffectsOptions struct {
	Effects []map[string]any
	// Mode is "mux" (default, video output) or "audio" (processed audio track).
	Mode string
	// Audio optionally replaces the video's audio track (mux mode only).
	Audio *Attachment
	// OutputFormat overrides the container of the produced artifact.
	OutputFormat string
	WebhookURL   string
}

VideoEffectsOptions controls POST /v1/video/effects.

Directories

Path Synopsis
Command example walks through the VoiceKit Go SDK.
Command example walks through the VoiceKit Go SDK.

Jump to

Keyboard shortcuts

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