Audio and speech
Play and loop sounds and streams, render PCM, record from a chosen microphone, show what is playing, recognize speech and speak text.
The audio package plays short sounds decoded once into memory (audio.LoadSound) and long streamed audio (audio.NewPlayer) where cx.Env().CanPlayAudio() is true; elsewhere calls fail with audio.Unavailable.
audio.LoadSound(cx, audio.Source{URI: "asset:sounds/click.wav"}, func(click *audio.Sound, err error) { if err != nil { return } click.Play(audio.Voice{}) // center, full volume, normal rate click.Play(audio.Voice{Volume: 0.5, Rate: 1.2, Pan: -0.5}) // overlaps, panned left})audio.Voice sets per-playback Volume (0 to 1, 0 as 1), Rate (0.5 to 2, 0 as 1) and Pan (-1 full left to 1 full right, 0 centered); values outside those ranges are clamped and NaN takes the default. Sound.Stop stops all playbacks of the sound and Close frees it, as its owning scope does when disposed. Player supports Play, Preload, Pause, Seek, SetVolume, SetRate, SetLoop and Close. macOS, iOS, Windows, Linux, Android and the web play audio today. Apple, Windows and browser backends support WAV, AAC and MP3. Linux uses GStreamer codecs, and its streamed player plays at 1×. Android pauses a player when its view leaves the screen and limits each decoded sound to 1 MiB. tvOS, watchOS, HarmonyOS and mini programs still report CanPlayAudio false.
Browsers require a user gesture for audible playback. Load short sounds ahead of time, then call Sound.Play after a click, tap or key press. A sound played before a gesture is silent. A player’s Play callback receives audio.NotAllowed if the browser blocks playback. Retry from a user gesture.
Sound.Play returns an audio.Playback, which on macOS, iOS, Windows, Linux, Android and the web can set its own volume, rate and pan or stop independently. Ended() is reactive and becomes true when that playback finishes, stops, is displaced by the voice limit, or cannot start. Backends without individual controls return an ended handle.
On iOS, an audio engine of a library’s own that plays outside audio and Video, such as an AudioQueue, holds the app’s one audio session with audio.HoldSession(core.AudioSessionPlayback) while it plays and calls the returned release when it stops. It takes the levels a player’s AudioSession does, beside the app’s videos, players and recordings, so AudioSessionPlayback and AudioSessionMixWithOthers keep playing with the Ring/Silent switch on silent. Elsewhere it holds nothing.
Use audio.Voice{Muted: true} to start an effect silently and playback.SetVolume(0) to silence an active effect. For long audio, audio.NewPlayer streams a source and player.SetMuted(true) silences the output while playback continues. Unmuting restores the player’s configured volume. Voice.Volume and Player.SetVolume use zero for default full volume.
Looping audio
Section titled “Looping audio”Set audio.Voice.Loop to repeat a sound playback until Stop or Close. For streamed music, set audio.PlayerOptions.LoopStart and call SetLoop(true). The first pass includes the intro. Later passes start at the offset. A zero offset repeats the full track.
On macOS 14 and iOS 17 or later, a finite track uses the native queue to prepare each repetition before the current one ends. Earlier Apple versions seek to the loop start when the current pass ends, with a short gap. On Linux and the web, a looping player decodes a track of up to 32 MiB and 5 minutes into memory, about 23 MB a minute, and repeats it without a gap. On Linux a larger or longer track streams through its own decoder and repeats without a gap too; on the web it seeks back at the end, with a short gap. On Windows and Android, a loop with a start seeks back to it at the end, with a short gap. On the web a looping player at a rate other than 1 seeks back at the end too, as the browser’s gapless playback would shift the pitch with the rate. On the web a looping player, like a sound, plays only after the user pressed something on the page, and fails with NotAllowed before that.
Audio timing
Section titled “Audio timing”Use audio.Now(cx) as the clock for timed playback. Set audio.Voice.StartAt to a future time when audio.CanSchedule(cx) is true. Call audio.OutputLatency(cx, func(latency time.Duration, known bool) { ... }) for the active output route. macOS, iOS, Linux and the web support timed starts; on Windows and Android CanSchedule is false and a StartAt plays at once. The callback’s known value tells whether the route reported a latency, which Windows and Android do not.
Sound limits
Section titled “Sound limits”Use audio.SetSoundLimits(cx, audio.SoundLimits{MaxSounds: 200, MaxDuration: 20 * time.Second}) before loading sounds to change the engine’s limits. MaxEncodedBytes, MaxDecodedBytes and MaxPlaybacks can also be set. Zero fields use the defaults of 8 MiB encoded and 5 seconds per sound, 64 sources, 16 MiB decoded across sounds, and 32 overlapping playbacks per output. Existing sounds stay loaded and count toward the new limits. Restricted scopes keep the default limits within the engine’s budget, whatever the app set. Android’s SoundPool plays at most 32 sounds at once and decodes at most 1 MiB of each, whatever the limits.
Pull PCM audio
Section titled “Pull PCM audio”Use audio.NewOutput(cx, audio.OutputConfig{SampleRate: 48000, Channels: 2, Render: render}) to play interleaved Float32 PCM your app decodes or synthesizes. Start begins pulling samples, Pause stops the pulls and the owning scope closes the output as it goes. macOS, iOS, Android, Windows, Linux, the web and mini games support this stream. Other targets return audio.ErrUnsupported.
Render returns the number of frames it filled. It runs on the audio thread and must avoid blocking, allocation and graph access. A short fill plays silence for the remainder and increments Underruns. Position returns the monotonic frame count and the host time at that frame. Use Flush to discard pending frames and Latency to read the buffer latency. Route changes and interruptions pause output and call OnInterrupt on the engine. The app can resume it with Start.
Choosing a microphone
Section titled “Choosing a microphone”microphone.Devices() lists the inputs the app can record from, such as the built-in microphone, a headset or a USB interface, each with an ID, a Name and whether it is the system’s Default. Put an ID in microphone.RecordOptions.Device, or pass it to microphone.CaptureFrom(id, rate, samples), to record from that input while the system’s default stays as it is; an empty ID records from the default. An ID no input has, such as a headset’s that was unplugged, fails with microphone.ErrNoDevice.
stop := microphone.WatchDevices(func() { inputs := microphone.Devices() cx.Post(func() { setInputs(inputs) })})cx.Cleanup(stop)WatchDevices calls its function on a goroutine of the package’s whenever an input connects or disconnects or the default changes. Listing needs no permission; recording still asks for the microphone. macOS lists its inputs; other targets list none yet and record from the default alone. In a headless test, nsgotest.Microphone.Devices sets what the app lists and RecordWAV records from, SetDevices changes it, and each Recorded names the device it came from; CaptureFrom is not faked and still checks an ID against the system’s real inputs.
Now Playing
Section titled “Now Playing”Use cx.SetNowPlaying(core.NowPlaying{...}) to show the app’s current media in macOS’s Control Center and menu bar. Supply Title, Artist, Album and optional Artwork as a *core.ImageSource. A zero Duration means a live stream. Give the current Position and playback Rate (zero while paused, one at normal speed). Publish again when the track, position or rate changes. The system advances the position between calls.
List the supported transport controls in Commands, such as core.MediaPlay, core.MediaPause, core.MediaTogglePlayPause and core.MediaSeek. Handle requests with cx.OnMediaCommand. The callback receives the command’s Kind and, for a seek, the requested Position. The newest live handler takes commands. Call cx.ClearNowPlaying() when the app is done playing. While the app publishes manually, controlled videos on macOS suspend their own publication. Check cx.Env().CanShowNowPlaying() for platform support.
Speech recognition
Section titled “Speech recognition”cx.StartSpeech recognizes speech with the system’s recognizer where cx.Env().CanRecognizeSpeech() says it exists (macOS, iOS, Android, Windows and browsers exposing SpeechRecognition or webkitSpeechRecognition), and answers with the transcript as it changes. On Apple platforms declare NSMicrophoneUsageDescription and NSSpeechRecognitionUsageDescription in apple.info; on Android add RECORD_AUDIO to android.permissions. In a headless test, app.Speech holds a nsgotest.SpeechSession while recognition is active. Use app.HearSpeech and app.EndSpeech to deliver results.
session, err := cx.StartSpeech(core.SpeechOptions{ Lang: "en-US", Interim: true, OnResult: func(text string, final bool) { transcript.Set(text) },})if err == nil { defer session.Stop()}Speaking text
Section titled “Speaking text”cx.Speak reads text aloud in the system’s voice for a language where cx.Env().CanSpeak() says the platform speaks: macOS, iOS, tvOS, watchOS, Android, Windows, the web and Linux with speech-dispatcher. One utterance speaks at a time: another Speak cuts the one speaking, and so do cx.StopSpeaking and the end of the scope that spoke it. done hears once how it ended: finished, stopped, or failed with a core.SpeakError, such as core.SpeakLanguageUnavailable when no voice installed speaks the language.
cx.Speak("Guten Morgen", core.Voice{Lang: "de-DE", Rate: 0.8}, func(stopped bool, err error) { speaking.Set(false)})Rate and Pitch run from 0.5 to 2, 1 being the voice’s own. cx.Voices("ja", ...) lists the voices installed for a language, so the app can ask the user to install one it lacks or let them pick one, whose ID goes in core.Voice. Browsers speak only after the user has pressed something on the page, and fail with core.SpeakNotAllowed before.
On mini programs, core WeChat (wx), QQ (qq), consumer Alipay (my) and Douyin (tt) provide no built-in client text-to-speech API, so cx.Env().CanSpeak() is false by default. On WeChat, an app that enables WeChat’s official WechatSI plugin (wx069ba97219f66d99) in the WeChat MP console and sets miniprogram.wechat_speech_plugin (such as "0.3.5") in nsgo.yaml gets zh-CN and en-US speech through WechatSI and InnerAudioContext (Rate from 0.5 to 2; Pitch is ignored); CanSpeak() becomes true only when the plugin is loaded at runtime.