### logging.FileLogger
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Logs SDK internals to a file. This is a process-wide singleton that routes diagnostic output. Filters can be applied to match specific log lines. The example shows how to start logging, set level and filters, and stop logging.
```APIDOC
## `logging.FileLogger` — Log SDK internals to a file
Process-wide singleton that routes SDK diagnostic output to a file. Filters are semicolon-separated, case-sensitive substrings matched against log lines.
```go
import "github.com/Microsoft/cognitive-services-speech-sdk-go/diagnostics/logging"
// Start file logging (append mode optional)
if err := logging.FileLogger.Start("/tmp/speech-sdk.log", false); err != nil {
panic(err)
}
logging.FileLogger.SetLevel(logging.Verbose)
logging.FileLogger.SetFilters("SPX_DBG_TRACE", "SPEECH")
// ... run recognizer / synthesizer operations ...
if err := logging.FileLogger.Stop(); err != nil {
panic(err)
}
```
```
--------------------------------
### dialog.NewCustomCommandsConfigFromSubscription
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Connects to an Azure Custom Commands app, designed for voice-forward task completion. It requires an application ID and subscription key. The example shows configuration, setting language, and initiating a connection to listen for a command.
```APIDOC
## `dialog.NewCustomCommandsConfigFromSubscription` — Connect to Azure Custom Commands app
For voice-forward task completion apps built with Azure Custom Commands. Requires an application ID in addition to a subscription key.
```go
ccConfig, err := dialog.NewCustomCommandsConfigFromSubscription(
"YourAppID", // Custom Commands application ID
"YourKey",
"westus2",
)
if err != nil { panic(err) }
defert ccConfig.Close()
// Optionally set input language
ccConfig.SetLanguage("en-US")
audioConfig, _ := audio.NewAudioConfigFromDefaultMicrophoneInput()
defert audioConfig.Close()
connector, _ := dialog.NewDialogServiceConnectorFromConfig(ccConfig, audioConfig)
defert connector.Close()
connector.ActivityReceived(func(e dialog.ActivityReceivedEventArgs) {
defer e.Close()
fmt.Println("Command response:", e.Activity)
})
connector.ConnectAsync()
outcome := <-connector.ListenOnceAsync()
defert outcome.Close()
fmt.Println("Command:", outcome.Result.Text)
```
```
--------------------------------
### logging.MemoryLogger
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Captures SDK logs in memory using a ring buffer. This is useful for inspecting diagnostics during tests or for post-mortem dumps on error. The example demonstrates starting logging, setting the level, inspecting logs, and optionally dumping them to a file on exit.
```APIDOC
## `logging.MemoryLogger` — Capture logs in memory for inspection
Stores log lines in an in-process ring buffer. Useful for capturing diagnostics during tests or for post-mortem dump on error.
```go
logging.MemoryLogger.Start()
logging.MemoryLogger.SetLevel(logging.Warning)
// ... run operations ...
// Inspect in-memory log
lines := logging.MemoryLogger.DumpToSlice()
for _, line := range lines {
fmt.Print(line)
}
// Or dump to file on exit
logging.MemoryLogger.DumpOnExit("/tmp/speech-errors.log", "[SPEECH] ", false, true)
logging.MemoryLogger.Stop()
```
```
--------------------------------
### Create PullStream for SDK to Read Audio Data
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Implement the `audio.PullAudioInputStreamCallback` interface to create a pull stream. The SDK will call your `Read` method to get audio chunks. Provide an implementation for `GetProperty` and `CloseStream` as well.
```go
// Pull stream: SDK calls your callback
type myCallback struct{}
func (c myCallback) Read(maxSize uint32) ([]byte, int) {
// return up to maxSize bytes of PCM audio
buf := make([]byte, maxSize)
n := readFromMySource(buf)
return buf[:n], n
}
func (c myCallback) GetProperty(id common.PropertyID) string { return "" }
func (c myCallback) CloseStream() {}
pullStream, err := audio.CreatePullStream(myCallback{})
if err != nil {
panic(err)
}
deferr pullStream.Close()
```
--------------------------------
### logging.EventLogger
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Receives SDK log lines in real time via a Go callback function. This is useful for forwarding SDK diagnostics into your own structured logger. The example shows setting the level, filters, and a callback function, and how to unregister the callback.
```APIDOC
## `logging.EventLogger` — Receive log lines via Go callback
Routes each SDK log line to a user-supplied Go function in real time. Useful for forwarding SDK diagnostics into your own structured logger (e.g., `zap`, `logrus`).
```go
logging.EventLogger.SetLevel(logging.Info)
logging.EventLogger.SetFilters("Recognition", "Synthesis")
err := logging.EventLogger.SetCallback(func(message string) {
// Forward to your application logger
myLogger.Debug("speech-sdk", "msg", message)
})
if err != nil { panic(err) }
// ... run operations ...
// Unregister callback
logging.EventLogger.SetCallback(nil)
```
```
--------------------------------
### SpeechSynthesizer.StartSpeakingTextAsync + AudioDataStream
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Enables streaming Text-to-Speech (TTS) with low latency by returning as soon as synthesis starts. Audio chunks can be consumed in real-time using AudioDataStream.
```APIDOC
## SpeechSynthesizer.StartSpeakingTextAsync + AudioDataStream
### Description
Streams Text-to-Speech (TTS) with low latency. `StartSpeakingTextAsync` returns when synthesis begins, allowing `AudioDataStream` to process audio chunks as they arrive, reducing the time to get the first audio output.
### Method Signature
`StartSpeakingTextAsync(text string) <-chan SpeechSynthesisOutcome`
### Usage
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
deferr config.Close()
synthesizer, _ := speech.NewSpeechSynthesizerFromConfig(config, nil)
deferr synthesizer.Close()
outcome := <-synthesizer.StartSpeakingTextAsync("Streaming synthesis reduces perceived latency.")
deferr outcome.Close()
if outcome.Error != nil { panic(outcome.Error) }
stream, err := speech.NewAudioDataStreamFromSpeechSynthesisResult(outcome.Result)
if err != nil { panic(err) }
deferr stream.Close()
var allAudio []byte
chunk := make([]byte, 4096)
for {
n, err := stream.Read(chunk)
if err != nil { break } // io.EOF when complete
allAudio = append(allAudio, chunk[:n]...)
// process/play chunk[:n] in real time
}
fmt.Printf("Streamed %d bytes total\n", len(allAudio))
```
```
--------------------------------
### dialog.NewBotFrameworkConfigFromSubscription + DialogServiceConnector
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Connects to a Bot Framework bot, enabling voice input/output to be linked to an Azure Bot Framework backend. It allows sending speech to the bot and receiving JSON activities back. The example demonstrates connecting, listening for an utterance, and sending a proactive activity.
```APIDOC
## `dialog.NewBotFrameworkConfigFromSubscription` + `DialogServiceConnector` — Connect to a Bot Framework bot
`DialogServiceConnector` links voice input/output to an Azure Bot Framework backend. It sends speech to the bot and receives bot activities (JSON) back. `ListenOnceAsync` captures one utterance and sends it; `SendActivityAsync` sends a raw Bot Framework activity JSON string.
```go
import (
"github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
"github.com/Microsoft/cognitive-services-speech-sdk-go/dialog"
"github.com/Microsoft/cognitive-services-speech-sdk-go/speech"
)
botConfig, err := dialog.NewBotFrameworkConfigFromSubscription("YourKey", "westus2")
if err != nil { panic(err) }
defert botConfig.Close()
audioConfig, _ := audio.NewAudioConfigFromDefaultMicrophoneInput()
defert audioConfig.Close()
connector, err := dialog.NewDialogServiceConnectorFromConfig(botConfig, audioConfig)
if err != nil { panic(err) }
defert connector.Close()
connector.SessionStarted(func(e speech.SessionEventArgs) {
defer e.Close()
fmt.Println("Session started:", e.SessionID)
})
connector.ActivityReceived(func(e dialog.ActivityReceivedEventArgs) {
defer e.Close()
fmt.Println("Bot activity:", e.Activity)
})
connector.Recognized(func(e speech.SpeechRecognitionEventArgs) {
defer e.Close()
fmt.Println("Recognized:", e.Result.Text)
})
// Connect then listen for one utterance
if err := <-connector.ConnectAsync(); err != nil { panic(err) }
outcome := <-connector.ListenOnceAsync()
defert outcome.Close()
if outcome.Error != nil { panic(outcome.Error) }
fmt.Println("User said:", outcome.Result.Text)
// Send a proactive activity to the bot
activityJSON := `{"type":"message","text":"Hello from Go"}`
sendOutcome := <-connector.SendActivityAsync(activityJSON)
fmt.Println("Interaction ID:", sendOutcome.InteractionID)
connector.DisconnectAsync()
```
```
--------------------------------
### Initialize and Use Loggers in Go
Source: https://github.com/microsoft/cognitive-services-speech-sdk-go/blob/master/diagnostics/README.md
Demonstrates how to set up and use various loggers (File, Memory, Event, Console) and control log levels. Ensure to stop loggers when no longer needed using defer.
```go
import "github.com/Microsoft/cognitive-services-speech-sdk-go/diagnostics/logging"
// File logging
logging.FileLogger.Start("/tmp/speech.log")
defer logging.FileLogger.Stop()
// Memory logging with dump
logging.MemoryLogger.Start()
defer logging.MemoryLogger.Stop()
logging.TraceInfo("recognized: %s", result.Text)
lines := logging.MemoryLogger.DumpToSlice()
// Event-based logging
logging.EventLogger.SetCallback(func(msg string) {
fmt.Println(msg)
})
defer logging.EventLogger.SetCallback(nil)
// Console logging
logging.ConsoleLogger.Start()
defer logging.ConsoleLogger.Stop()
// Set log level
logging.FileLogger.SetLevel(logging.Error)
```
--------------------------------
### Synthesize Plain Text to Audio in Go
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Utilize `NewSpeechSynthesizerFromConfig` and `SpeakTextAsync` to convert plain text into audio. This method synchronously waits for the full synthesis to complete. The resulting `AudioData` contains raw PCM audio bytes. An `AudioConfig` can be provided to play audio directly, or `nil` to capture it programmatically.
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
defers config.Close()
config.SetSpeechSynthesisVoiceName("en-US-JennyNeural")
// Synthesize to default speaker
audioConfig, _ := audio.NewAudioConfigFromDefaultSpeakerOutput()
defers audioConfig.Close()
synthesizer, err := speech.NewSpeechSynthesizerFromConfig(config, audioConfig)
if err != nil { panic(err) }
defers synthesizer.Close()
outcome := <-synthesizer.SpeakTextAsync("Hello, welcome to the Azure Speech SDK for Go.")
defers outcome.Close()
if outcome.Error != nil { panic(outcome.Error) }
fmt.Printf("Synthesis complete. Audio duration: %v, bytes: %d\n",
outcome.Result.AudioDuration, len(outcome.Result.AudioData))
// Output: Synthesis complete. Audio duration: 2.34s, bytes: 74880
```
--------------------------------
### Build Go Tests with CMake
Source: https://github.com/microsoft/cognitive-services-speech-sdk-go/blob/master/diagnostics/README.md
Instructions for building Go integration tests using CMake, including options for standard and race detection builds.
```bash
cmake --build build --target go-tests --config Release
```
```bash
cmake --build build --target go-tests-race --config Release
```
--------------------------------
### Configure Audio Input and Output Sources
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Defines the audio source for recognition or the destination for synthesis. Supports default microphone, WAV files, and speaker output. Pass nil to a synthesizer to suppress speaker output.
```go
import "github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
// Microphone input
micConfig, err := audio.NewAudioConfigFromDefaultMicrophoneInput()
if err != nil { panic(err) }
defmicConfig.Close()
// WAV file input
fileConfig, err := audio.NewAudioConfigFromWavFileInput("speech.wav")
if err != nil { panic(err) }
defileConfig.Close()
// WAV file output (for TTS)
outConfig, err := audio.NewAudioConfigFromWavFileOutput("output.wav")
if err != nil { panic(err) }
defoutConfig.Close()
// Default speaker output (for TTS)
speakerConfig, err := audio.NewAudioConfigFromDefaultSpeakerOutput()
if err != nil { panic(err) }
defspeakerConfig.Close()
```
--------------------------------
### Create Speech Config from Subscription Key
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Use this to initialize speech configuration with your Azure subscription key and region. Remember to close the config when done. Optional settings like language and voice can be customized.
```go
import "github.com/Microsoft/cognitive-services-speech-sdk-go/speech"
config, err := speech.NewSpeechConfigFromSubscription("YourSubscriptionKey", "eastus")
if err != nil {
panic(err)
}
defconfig.Close()
// Optional: customize language, output format, profanity filter, etc.
config.SetSpeechRecognitionLanguage("en-US")
config.SetSpeechSynthesisVoiceName("en-US-AriaNeural")
config.SetSpeechSynthesisLanguage("en-US")
config.RequestWordLevelTimestamps()
config.EnableAudioLogging()
// Output: config ready for recognizer/synthesizer creation
```
--------------------------------
### Custom Audio Streams: Push and Pull
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Demonstrates how to create custom audio input streams for the Speech SDK. `PushAudioInputStream` allows the application to push audio data, while `PullAudioInputStream` enables the SDK to pull audio data via a callback.
```APIDOC
## Custom Audio Streams
`PushAudioInputStream` lets the application push PCM/WAV bytes into the recognizer. `PullAudioInputStream` inverts control — the SDK calls a user-supplied callback to pull audio chunks.
### Push Stream Example
```go
// Push stream: application writes audio data
stream, err := audio.CreatePushAudioInputStream() // default: 16 kHz 16-bit mono PCM
if err != nil { panic(err) }
defer stream.Close()
audioConfig, _ := audio.NewAudioConfigFromStreamInput(stream)
defer audioConfig.Close()
// Write raw PCM bytes (no WAV header) in chunks
pcmBytes := make([]byte, 3200) // 100ms of 16kHz 16-bit mono
// ... fill pcmBytes from your source ...
if err := stream.Write(pcmBytes); err != nil { panic(err) }
stream.CloseStream() // signal end of audio
```
### Pull Stream Example
```go
// Pull stream: SDK calls your callback
type myCallback struct{}
func (c myCallback) Read(maxSize uint32) ([]byte, int) {
// return up to maxSize bytes of PCM audio
buf := make([]byte, maxSize)
n := readFromMySource(buf)
return buf[:n], n
}
func (c myCallback) GetProperty(id common.PropertyID) string { return "" }
func (c myCallback) CloseStream() {}
pullStream, err := audio.CreatePullStream(myCallback{})
if err != nil { panic(err) }
defer pullStream.Close()
```
```
--------------------------------
### Create PushAudioInputStream for Sending Audio Data
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Use `CreatePushAudioInputStream` to create a stream where your application pushes audio data. The default format is 16 kHz, 16-bit mono PCM. Ensure to close the stream when done and signal the end of audio with `CloseStream()`.
```go
// Push stream: application writes audio data
stream, err := audio.CreatePushAudioInputStream() // default: 16 kHz 16-bit mono PCM
if err != nil {
panic(err)
}
defer stream.Close()
audioConfig, _ := audio.NewAudioConfigFromStreamInput(stream)
deferr audioConfig.Close()
// Write raw PCM bytes (no WAV header) in chunks
pcmBytes := make([]byte, 3200) // 100ms of 16kHz 16-bit mono
// ... fill pcmBytes from your source ...
if err := stream.Write(pcmBytes); err != nil {
panic(err)
}
stream.CloseStream() // signal end of audio
```
--------------------------------
### Receive log lines via Go callback using EventLogger
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Configure `EventLogger` to route each SDK log line to a user-supplied Go function in real time. This allows forwarding diagnostics to your own structured logger. Remember to unregister the callback when no longer needed.
```go
logging.EventLogger.SetLevel(logging.Info)
logging.EventLogger.SetFilters("Recognition", "Synthesis")
err := logging.EventLogger.SetCallback(func(message string) {
// Forward to your application logger
myLogger.Debug("speech-sdk", "msg", message)
})
if err != nil { panic(err) }
// ... run operations ...
// Unregister callback
logging.EventLogger.SetCallback(nil)
```
--------------------------------
### Boost Recognition Accuracy with Phrase Lists in Go
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Employ `PhraseListGrammar` to enhance recognition accuracy by providing a list of expected phrases. Use `SetWeight` to increase the probability of these phrases being recognized. Remember to clear the grammar if needed before subsequent recognition sessions.
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
defers config.Close()
audioConfig, _ := audio.NewAudioConfigFromDefaultMicrophoneInput()
defers audioConfig.Close()
recognizer, _ := speech.NewSpeechRecognizerFromConfig(config, audioConfig)
defers recognizer.Close()
grammar, err := speech.NewPhraseListGrammarFromRecognizer(recognizer)
if err != nil { panic(err) }
defers grammar.Close()
grammar.AddPhrase("Wreck a nice beach")
grammar.AddPhrase("Recognize speech")
grammar.AddPhrase("Cortana")
grammar.SetWeight(3.0) // higher weight = stronger bias
outcome := <-recognizer.RecognizeOnceAsync()
defers outcome.Close()
fmt.Println("Recognized:", outcome.Result.Text)
// grammar.Clear() to remove all phrases before the next recognition session
```
--------------------------------
### speech.NewSpeechConfigFromSubscription
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Creates a SpeechConfig object using an Azure subscription key and region. This is the primary entry point for SDK features and must be closed with defer config.Close().
```APIDOC
## speech.NewSpeechConfigFromSubscription
### Description
Creates a SpeechConfig object using an Azure subscription key and region. This is the primary entry point for SDK features and must be closed with defer config.Close().
### Method
`speech.NewSpeechConfigFromSubscription(subscriptionKey string, region string) (*SpeechConfig, error)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
import "github.com/Microsoft/cognitive-services-speech-sdk-go/speech"
config, err := speech.NewSpeechConfigFromSubscription("YourSubscriptionKey", "eastus")
if err != nil {
panic(err)
}
def config.Close()
// Optional: customize language, output format, profanity filter, etc.
config.SetSpeechRecognitionLanguage("en-US")
config.SetSpeechSynthesisVoiceName("en-US-AriaNeural")
config.SetSpeechSynthesisLanguage("en-US")
config.RequestWordLevelTimestamps()
config.EnableAudioLogging()
```
### Response
#### Success Response (200)
`*SpeechConfig` object used to construct recognizers, synthesizers, and dialog connectors.
#### Response Example
None provided
```
--------------------------------
### Connect to Custom Commands using DialogServiceConnector
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Use `DialogServiceConnector` with `CustomCommandsConfig` for voice-forward task completion apps. This requires an application ID and subscription key. The language can be optionally set.
```go
ccConfig, err := dialog.NewCustomCommandsConfigFromSubscription(
"YourAppID", // Custom Commands application ID
"YourKey",
"westus2",
)
if err != nil { panic(err) }
defers ccConfig.Close()
// Optionally set input language
ccConfig.SetLanguage("en-US")
audioConfig, _ := audio.NewAudioConfigFromDefaultMicrophoneInput()
defers audioConfig.Close()
connector, _ := dialog.NewDialogServiceConnectorFromConfig(ccConfig, audioConfig)
defers connector.Close()
connector.ActivityReceived(func(e dialog.ActivityReceivedEventArgs) {
defer e.Close()
fmt.Println("Command response:", e.Activity)
})
connector.ConnectAsync()
outcome := <-connector.ListenOnceAsync()
defers outcome.Close()
fmt.Println("Command:", outcome.Result.Text)
```
--------------------------------
### Create Speech Config from Custom Endpoint
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Use this for custom endpoints, sovereign clouds, or non-standard deployments. Query parameters in the endpoint URI override other configuration settings.
```go
config, err := speech.NewSpeechConfigFromEndpointWithSubscription(
"wss://myregion.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1",
"YourSubscriptionKey",
)
if err != nil {
panic(err)
}
defconfig.Close()
```
--------------------------------
### Log SDK internals to a file using FileLogger
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Configure `FileLogger` to route SDK diagnostic output to a file. You can specify filters and log levels. Ensure to stop the logger when done.
```go
import "github.com/Microsoft/cognitive-services-speech-sdk-go/diagnostics/logging"
// Start file logging (append mode optional)
if err := logging.FileLogger.Start("/tmp/speech-sdk.log", false); err != nil {
panic(err)
}
logging.FileLogger.SetLevel(logging.Verbose)
logging.FileLogger.SetFilters("SPX_DBG_TRACE", "SPEECH")
// ... run recognizer / synthesizer operations ...
if err := logging.FileLogger.Stop(); err != nil {
panic(err)
}
```
--------------------------------
### Create Speech Config from Authorization Token
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Initialize speech configuration using a short-lived authorization token. The caller must manage token refresh before expiry by calling `SetAuthorizationToken`.
```go
config, err := speech.NewSpeechConfigFromAuthorizationToken("Bearer eyJ...", "eastus")
if err != nil {
panic(err)
}
defconfig.Close()
// Refresh token before expiry (tokens are valid ~10 minutes)
config.SetAuthorizationToken("Bearer eyJrefreshed...")
```
--------------------------------
### audio.NewAudioConfigFromDefaultMicrophoneInput
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Creates an AudioConfig object for default microphone input. This object defines where audio comes from or where synthesized audio goes.
```APIDOC
## audio.NewAudioConfigFromDefaultMicrophoneInput
### Description
Creates an AudioConfig object for default microphone input. This object defines where audio comes from or where synthesized audio goes. Pass `nil` as `audioConfig` to a synthesizer to suppress speaker output.
### Method
`audio.NewAudioConfigFromDefaultMicrophoneInput() (*AudioConfig, error)`
### Parameters
None
### Request Example
```go
import "github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
micConfig, err := audio.NewAudioConfigFromDefaultMicrophoneInput()
if err != nil { panic(err) }
def micConfig.Close()
```
### Response
#### Success Response (200)
`*AudioConfig` object for microphone input.
#### Response Example
None provided
```
--------------------------------
### Single-utterance Recognition with RecognizeOnceAsync
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Use `RecognizeOnceAsync` for command and query scenarios where only a single utterance needs recognition. Results are delivered on a channel with a recommended 5-second timeout. Ensure to import necessary packages like `fmt`, `time`, and the speech SDK modules.
```go
import (
"fmt"
"time"
"github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
"github.com/Microsoft/cognitive-services-speech-sdk-go/speech"
)
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
deferr config.Close()
audioConfig, _ := audio.NewAudioConfigFromWavFileInput("command.wav")
deferr audioConfig.Close()
recognizer, err := speech.NewSpeechRecognizerFromConfig(config, audioConfig)
if err != nil {
panic(err)
}
deferr recognizer.Close()
task := recognizer.RecognizeOnceAsync()
var outcome speech.SpeechRecognitionOutcome
select {
case outcome = <-task:
case <-time.After(5 * time.Second):
fmt.Println("Timed out")
return
}
deferr outcome.Close()
if outcome.Error != nil {
fmt.Println("Error:", outcome.Error)
return
}
fmt.Println("Recognized:", outcome.Result.Text)
// Output: Recognized: Turn the lights on
```
--------------------------------
### audio.NewAudioConfigFromWavFileInput
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Creates an AudioConfig object for reading audio from a WAV file. This object defines where audio comes from or where synthesized audio goes.
```APIDOC
## audio.NewAudioConfigFromWavFileInput
### Description
Creates an AudioConfig object for reading audio from a WAV file. This object defines where audio comes from or where synthesized audio goes. Pass `nil` as `audioConfig` to a synthesizer to suppress speaker output.
### Method
`audio.NewAudioConfigFromWavFileInput(filePath string) (*AudioConfig, error)`
### Parameters
#### Path Parameters
- **filePath** (string) - Required - The path to the WAV file.
### Request Example
```go
import "github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
fileConfig, err := audio.NewAudioConfigFromWavFileInput("speech.wav")
if err != nil { panic(err) }
def fileConfig.Close()
```
### Response
#### Success Response (200)
`*AudioConfig` object for WAV file input.
#### Response Example
None provided
```
--------------------------------
### Connect to Bot Framework using DialogServiceConnector
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Use `DialogServiceConnector` to link voice input/output to an Azure Bot Framework backend. This snippet shows how to set up the connector, handle session events, receive bot activities, and process recognized speech.
```go
import (
"github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
"github.com/Microsoft/cognitive-services-speech-sdk-go/dialog"
"github.com/Microsoft/cognitive-services-speech-sdk-go/speech"
)
botConfig, err := dialog.NewBotFrameworkConfigFromSubscription("YourKey", "westus2")
if err != nil { panic(err) }
defers botConfig.Close()
audioConfig, _ := audio.NewAudioConfigFromDefaultMicrophoneInput()
defers audioConfig.Close()
connector, err := dialog.NewDialogServiceConnectorFromConfig(botConfig, audioConfig)
if err != nil { panic(err) }
defers connector.Close()
connector.SessionStarted(func(e speech.SessionEventArgs) {
defer e.Close()
fmt.Println("Session started:", e.SessionID)
})
connector.ActivityReceived(func(e dialog.ActivityReceivedEventArgs) {
defer e.Close()
fmt.Println("Bot activity:", e.Activity)
})
connector.Recognized(func(e speech.SpeechRecognitionEventArgs) {
defer e.Close()
fmt.Println("Recognized:", e.Result.Text)
})
// Connect then listen for one utterance
if err := <-connector.ConnectAsync(); err != nil { panic(err) }
outcome := <-connector.ListenOnceAsync()
defers outcome.Close()
if outcome.Error != nil { panic(outcome.Error) }
fmt.Println("User said:", outcome.Result.Text)
// Send a proactive activity to the bot
activityJSON := `{"type":"message","text":"Hello from Go"}`
sendOutcome := <-connector.SendActivityAsync(activityJSON)
fmt.Println("Interaction ID:", sendOutcome.InteractionID)
connector.DisconnectAsync()
```
--------------------------------
### Continuous Recognition with Event Callbacks
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
For long-running recognition, use `StartContinuousRecognitionAsync`. Register handlers for `Recognizing` (intermediate results), `Recognized` (final results), and `Canceled` events. Stop recognition using `StopContinuousRecognitionAsync`. Ensure to close events and defer closing recognizer and config.
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
deferr config.Close()
audioConfig, _ := audio.NewAudioConfigFromDefaultMicrophoneInput()
deferr audioConfig.Close()
recognizer, _ := speech.NewSpeechRecognizerFromConfig(config, audioConfig)
deferr recognizer.Close()
recognizer.Recognizing(func(event speech.SpeechRecognitionEventArgs) {
defer event.Close()
fmt.Println("Recognizing:", event.Result.Text)
})
recognizer.Recognized(func(event speech.SpeechRecognitionEventArgs) {
defer event.Close()
fmt.Println("Recognized:", event.Result.Text)
})
recognizer.Canceled(func(event speech.SpeechRecognitionCanceledEventArgs) {
defer event.Close()
fmt.Println("Canceled:", event.ErrorDetails, "Reason:", event.Reason)
})
recognizer.SessionStarted(func(event speech.SessionEventArgs) {
defer event.Close()
fmt.Println("Session started, ID:", event.SessionID)
})
if err := <-recognizer.StartContinuousRecognitionAsync(); err != nil {
panic(err)
}
// ... application runs, audio is captured and recognized continuously ...
if err := <-recognizer.StopContinuousRecognitionAsync(); err != nil {
panic(err)
}
```
--------------------------------
### speech.NewSpeechSynthesizerFromConfig + SpeakTextAsync
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Synthesize plain text to audio synchronously. The result contains the raw PCM audio bytes in `AudioData`. Pass a speaker `AudioConfig` to play directly, or `nil` to capture audio programmatically.
```APIDOC
## speech.NewSpeechSynthesizerFromConfig + SpeakTextAsync — Synthesize plain text to audio
### Description
`SpeakTextAsync` converts plain text to audio synchronously (waits for full synthesis to complete). The result contains the raw PCM audio bytes in `AudioData`. Pass a speaker `AudioConfig` to play directly, or `nil` to capture audio programmatically.
### Method Signatures
`speech.NewSpeechSynthesizerFromConfig(config SpeechConfig, audioConfig AudioConfig) (*SpeechSynthesizer, error)`
`synthesizer.SpeakTextAsync(text string) <-chan SpeechSynthesisOutcome`
### Usage Example
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
defer config.Close()
config.SetSpeechSynthesisVoiceName("en-US-JennyNeural")
// Synthesize to default speaker
audioConfig, _ := audio.NewAudioConfigFromDefaultSpeakerOutput()
defer audioConfig.Close()
synthesizer, err := speech.NewSpeechSynthesizerFromConfig(config, audioConfig)
if err != nil { panic(err) }
defer synthesizer.Close()
outcome := <-synthesizer.SpeakTextAsync("Hello, welcome to the Azure Speech SDK for Go.")
defer outcome.Close()
if outcome.Error != nil { panic(outcome.Error) }
fmt.Printf("Synthesis complete. Audio duration: %v, bytes: %d\n",
outcome.Result.AudioDuration, len(outcome.Result.AudioData))
// Output: Synthesis complete. Audio duration: 2.34s, bytes: 74880
```
```
--------------------------------
### audio.NewAudioConfigFromWavFileOutput
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Creates an AudioConfig object for writing synthesized audio to a WAV file. This object defines where audio comes from or where synthesized audio goes.
```APIDOC
## audio.NewAudioConfigFromWavFileOutput
### Description
Creates an AudioConfig object for writing synthesized audio to a WAV file. This object defines where audio comes from or where synthesized audio goes. Pass `nil` as `audioConfig` to a synthesizer to suppress speaker output.
### Method
`audio.NewAudioConfigFromWavFileOutput(filePath string) (*AudioConfig, error)`
### Parameters
#### Path Parameters
- **filePath** (string) - Required - The path for the output WAV file.
### Request Example
```go
import "github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
outConfig, err := audio.NewAudioConfigFromWavFileOutput("output.wav")
if err != nil { panic(err) }
def outConfig.Close()
```
### Response
#### Success Response (200)
`*AudioConfig` object for WAV file output.
#### Response Example
None provided
```
--------------------------------
### Automatic Language Detection with Go Speech SDK
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Use `NewSpeechRecognizerFromAutoDetectSourceLangConfig` to automatically detect the spoken language from a candidate list. The detected language is available in `SpeechRecognitionResult.Properties`. Ensure the correct language codes are provided.
```go
langConfig, err := speech.NewAutoDetectSourceLanguageConfigFromLanguages([]string{"en-US", "zh-CN", "fr-FR"})
if err != nil { panic(err) }
defers langConfig.Close()
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
defers config.Close()
audioConfig, _ := audio.NewAudioConfigFromWavFileInput("multilingual.wav")
defers audioConfig.Close()
recognizer, _ := speech.NewSpeechRecognizerFromAutoDetectSourceLangConfig(config, langConfig, audioConfig)
defers recognizer.Close()
outcome := <-recognizer.RecognizeOnceAsync()
defers outcome.Close()
if outcome.Error != nil { panic(outcome.Error) }
detectedLang := outcome.Result.Properties.GetPropertyByString("SpeechServiceConnection_AutoDetectSourceLanguageResult", "")
fmt.Printf("Detected language: %s, Text: %s\n", detectedLang, outcome.Result.Text)
// Output: Detected language: zh-CN, Text: 你好世界
```
--------------------------------
### speech.NewSpeechConfigFromEndpointWithSubscription
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Creates a SpeechConfig object targeting a custom endpoint using a subscription key. This is intended for sovereign clouds, private endpoints, or non-standard deployments.
```APIDOC
## speech.NewSpeechConfigFromEndpointWithSubscription
### Description
Creates a SpeechConfig object targeting a custom endpoint using a subscription key. This is intended for sovereign clouds, private endpoints, or non-standard deployments. Query parameters embedded in the endpoint URI always take precedence over values set via other config methods.
### Method
`speech.NewSpeechConfigFromEndpointWithSubscription(endpoint string, subscriptionKey string) (*SpeechConfig, error)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
config, err := speech.NewSpeechConfigFromEndpointWithSubscription(
"wss://myregion.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1",
"YourSubscriptionKey",
)
if err != nil {
panic(err)
}
def config.Close()
```
### Response
#### Success Response (200)
`*SpeechConfig` object.
#### Response Example
None provided
```
--------------------------------
### Stream TTS with AudioDataStream
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Use `StartSpeakingTextAsync` and `AudioDataStream` for low-latency audio streaming. Consume audio chunks as they arrive to reduce time-to-first-audio.
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
defers config.Close()
synthesizer, _ := speech.NewSpeechSynthesizerFromConfig(config, nil)
defers synthesizer.Close()
outcome := <-synthesizer.StartSpeakingTextAsync("Streaming synthesis reduces perceived latency.")
defers outcome.Close()
if outcome.Error != nil { panic(outcome.Error) }
stream, err := speech.NewAudioDataStreamFromSpeechSynthesisResult(outcome.Result)
if err != nil { panic(err) }
defers stream.Close()
var allAudio []byte
chunk := make([]byte, 4096)
for {
n, err := stream.Read(chunk)
if err != nil { break } // io.EOF when complete
allAudio = append(allAudio, chunk[:n]...)
// process/play chunk[:n] in real time
}
fmt.Printf("Streamed %d bytes total\n", len(allAudio))
```
--------------------------------
### List Available Voices
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Retrieve a list of available neural and standard voices using `GetVoicesAsync`. Optionally filter by locale by providing a locale string.
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
defers config.Close()
synthesizer, _ := speech.NewSpeechSynthesizerFromConfig(config, nil)
defers synthesizer.Close()
voicesOutcome := <-synthesizer.GetVoicesAsync("en-US") // empty string for all locales
defers voicesOutcome.Close()
if voicesOutcome.Error != nil { panic(voicesOutcome.Error) }
for _, voice := range voicesOutcome.Result.Voices {
fmt.Printf("Name: %-40s Locale: %s Gender: %v\n",
voice.Name, voice.Locale, voice.Gender)
}
// Output:
// Name: Microsoft Server Speech TTS en-US AriaNeural Locale: en-US Gender: Female
// Name: Microsoft Server Speech TTS en-US GuyNeural Locale: en-US Gender: Male
```
--------------------------------
### audio.NewAudioConfigFromDefaultSpeakerOutput
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Creates an AudioConfig object for default speaker output for synthesized audio. This object defines where audio comes from or where synthesized audio goes.
```APIDOC
## audio.NewAudioConfigFromDefaultSpeakerOutput
### Description
Creates an AudioConfig object for default speaker output for synthesized audio. This object defines where audio comes from or where synthesized audio goes. Pass `nil` as `audioConfig` to a synthesizer to suppress speaker output.
### Method
`audio.NewAudioConfigFromDefaultSpeakerOutput() (*AudioConfig, error)`
### Parameters
None
### Request Example
```go
import "github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
speakerConfig, err := audio.NewAudioConfigFromDefaultSpeakerOutput()
if err != nil { panic(err) }
def speakerConfig.Close()
```
### Response
#### Success Response (200)
`*AudioConfig` object for default speaker output.
#### Response Example
None provided
```
--------------------------------
### Synthesize SSML Markup to Audio in Go
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Use `SpeechSynthesizer.SpeakSsmlAsync` to synthesize audio from Speech Synthesis Markup Language (SSML). This provides fine-grained control over voice, pitch, rate, pauses, and phonemes. The synthesized audio bytes can be saved to a file.
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
defers config.Close()
synthesizer, _ := speech.NewSpeechSynthesizerFromConfig(config, nil) // nil = no audio output device
defers synthesizer.Close()
ssml := `
This is synthesized at a slower rate.
Important announcement!
`
outcome := <-synthesizer.SpeakSsmlAsync(ssml)
defers outcome.Close()
if outcome.Error != nil { panic(outcome.Error) }
// Save audio bytes to a file
os.WriteFile("output.wav", outcome.Result.AudioData, 0644)
fmt.Println("Saved", len(outcome.Result.AudioData), "bytes")
```
--------------------------------
### Capture logs in memory using MemoryLogger
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Use `MemoryLogger` to store log lines in an in-process ring buffer. This is useful for testing or post-mortem analysis. Logs can be dumped to a slice or a file.
```go
logging.MemoryLogger.Start()
logging.MemoryLogger.SetLevel(logging.Warning)
// ... run operations ...
// Inspect in-memory log
lines := logging.MemoryLogger.DumpToSlice()
for _, line := range lines {
fmt.Print(line)
}
// Or dump to file on exit
logging.MemoryLogger.DumpOnExit("/tmp/speech-errors.log", "[SPEECH] ", false, true)
logging.MemoryLogger.Stop()
```
--------------------------------
### speech.NewSpeechConfigFromAuthorizationToken
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Creates a SpeechConfig object using a short-lived authorization token and region. The caller is responsible for refreshing the token before it expires.
```APIDOC
## speech.NewSpeechConfigFromAuthorizationToken
### Description
Creates a SpeechConfig object using a short-lived authorization token and region. The caller is responsible for refreshing the token before it expires.
### Method
`speech.NewSpeechConfigFromAuthorizationToken(token string, region string) (*SpeechConfig, error)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```go
config, err := speech.NewSpeechConfigFromAuthorizationToken("Bearer eyJ...", "eastus")
if err != nil {
panic(err)
}
def config.Close()
// Refresh token before expiry (tokens are valid ~10 minutes)
config.SetAuthorizationToken("Bearer eyJrefreshed...")
```
### Response
#### Success Response (200)
`*SpeechConfig` object.
#### Response Example
None provided
```
--------------------------------
### SpeechSynthesizer.SpeakSsmlAsync
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Synthesize SSML markup for fine-grained control over voice, pitch, rate, pauses, and phonemes.
```APIDOC
## SpeechSynthesizer.SpeakSsmlAsync — Synthesize SSML markup
### Description
Accepts Speech Synthesis Markup Language (SSML) for fine-grained control over voice, pitch, rate, pauses, and phonemes.
### Method Signature
`synthesizer.SpeakSsmlAsync(ssml string) <-chan SpeechSynthesisOutcome`
### Usage Example
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
defer config.Close()
synthesizer, _ := speech.NewSpeechSynthesizerFromConfig(config, nil) // nil = no audio output device
defer synthesizer.Close()
ssml := `
This is synthesized at a slower rate.
Important announcement!
`
outcome := <-synthesizer.SpeakSsmlAsync(ssml)
defer outcome.Close()
if outcome.Error != nil { panic(outcome.Error) }
// Save audio bytes to a file
os.WriteFile("output.wav", outcome.Result.AudioData, 0644)
fmt.Println("Saved", len(outcome.Result.AudioData), "bytes")
```
```
--------------------------------
### SpeechSynthesizer.GetVoicesAsync
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Retrieves a list of available neural and standard voices, with an option to filter by locale.
```APIDOC
## SpeechSynthesizer.GetVoicesAsync
### Description
Retrieves the list of available neural and standard voices. You can optionally filter the results by specifying a locale.
### Method Signature
`GetVoicesAsync(locale string) <-chan VoiceResultOutcome`
### Usage
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
deferr config.Close()
synthesizer, _ := speech.NewSpeechSynthesizerFromConfig(config, nil)
deferr synthesizer.Close()
voicesOutcome := <-synthesizer.GetVoicesAsync("en-US") // empty string for all locales
deferr voicesOutcome.Close()
if voicesOutcome.Error != nil { panic(voicesOutcome.Error) }
for _, voice := range voicesOutcome.Result.Voices {
fmt.Printf("Name: %-40s Locale: %s Gender: %v\n",
voice.Name, voice.Locale, voice.Gender)
}
// Example Output:
// Name: Microsoft Server Speech TTS en-US AriaNeural Locale: en-US Gender: Female
// Name: Microsoft Server Speech TTS en-US GuyNeural Locale: en-US Gender: Male
```
```
--------------------------------
### Continuous Recognition
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Enables continuous speech recognition for long-running or multi-utterance scenarios. This involves registering event handlers for intermediate (`Recognizing`), final (`Recognized`), and `Canceled` events. Recognition is stopped using `StopContinuousRecognitionAsync`.
```APIDOC
### `SpeechRecognizer.StartContinuousRecognitionAsync` — Continuous recognition with event callbacks
For long-running or multi-utterance recognition. Register handlers for `Recognizing` (intermediate), `Recognized` (final), and `Canceled` events. Stop with `StopContinuousRecognitionAsync`.
```go
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
defer config.Close()
audioConfig, _ := audio.NewAudioConfigFromDefaultMicrophoneInput()
defer audioConfig.Close()
recognizer, _ := speech.NewSpeechRecognizerFromConfig(config, audioConfig)
defer recognizer.Close()
recognizer.Recognizing(func(event speech.SpeechRecognitionEventArgs) {
defer event.Close()
fmt.Println("Recognizing:", event.Result.Text)
})
recognizer.Recognized(func(event speech.SpeechRecognitionEventArgs) {
defer event.Close()
fmt.Println("Recognized:", event.Result.Text)
})
recognizer.Canceled(func(event speech.SpeechRecognitionCanceledEventArgs) {
defer event.Close()
fmt.Println("Canceled:", event.ErrorDetails, "Reason:", event.Reason)
})
recognizer.SessionStarted(func(event speech.SessionEventArgs) {
defer event.Close()
fmt.Println("Session started, ID:", event.SessionID)
})
if err := <-recognizer.StartContinuousRecognitionAsync(); err != nil {
panic(err)
}
// ... application runs, audio is captured and recognized continuously ...
if err := <-recognizer.StopContinuousRecognitionAsync(); err != nil {
panic(err)
}
```
```
--------------------------------
### speech.NewSpeechRecognizerFromAutoDetectSourceLangConfig
Source: https://context7.com/microsoft/cognitive-services-speech-sdk-go/llms.txt
Detects the spoken language automatically from a candidate list. The recognized language is available in `SpeechRecognitionResult.Properties`.
```APIDOC
## speech.NewSpeechRecognizerFromAutoDetectSourceLangConfig — Automatic language detection
### Description
Detects the spoken language automatically from a candidate list. The recognized language is available in `SpeechRecognitionResult.Properties`.
### Method Signature
`speech.NewSpeechRecognizerFromAutoDetectSourceLangConfig(config SpeechConfig, langConfig AutoDetectSourceLanguageConfig, audioConfig AudioConfig) (*SpeechRecognizer, error)`
### Usage Example
```go
langConfig, err := speech.NewAutoDetectSourceLanguageConfigFromLanguages([]string{"en-US", "zh-CN", "fr-FR"})
if err != nil { panic(err) }
defer langConfig.Close()
config, _ := speech.NewSpeechConfigFromSubscription("YourKey", "eastus")
defer config.Close()
audioConfig, _ := audio.NewAudioConfigFromWavFileInput("multilingual.wav")
defer audioConfig.Close()
recognizer, _ := speech.NewSpeechRecognizerFromAutoDetectSourceLangConfig(config, langConfig, audioConfig)
defer recognizer.Close()
outcome := <-recognizer.RecognizeOnceAsync()
defer outcome.Close()
if outcome.Error != nil { panic(outcome.Error) }
detectedLang := outcome.Result.Properties.GetPropertyByString("SpeechServiceConnection_AutoDetectSourceLanguageResult", "")
fmt.Printf("Detected language: %s, Text: %s\n", detectedLang, outcome.Result.Text)
// Output: Detected language: zh-CN, Text: 你好世界
```
```