audio

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-2-Clause Imports: 7 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package audio defines the interfaces for pluggable audio processing a transport applies to the media it sends and receives. A Filter transforms incoming audio (noise reduction, say) before it enters the pipeline; a Mixer blends auxiliary audio (background music, say) into the outgoing audio. Concrete implementations live in the audio subpackages (rnnoise, noise, mixer).

Index

Constants

View Source
const DefaultPreSpeech = time.Second

DefaultPreSpeech is how much audio a SpeechSegmentBuffer keeps from before speech starts by default. The VAD can report speech most of a second after it starts.

Variables

This section is empty.

Functions

func ALawToPCM added in v0.1.0

func ALawToPCM(alaw []byte, r *resample.Resampler) []byte

ALawToPCM decodes G.711 A-law to 16-bit PCM and converts it to the rate r runs at. A nil r leaves the rate alone. See ULawToPCM.

func InterleaveStereo added in v0.1.0

func InterleaveStereo(left, right []byte) []byte

InterleaveStereo weaves two mono streams of 16-bit signed PCM into one stereo stream, left channel first (L, R, L, R and so on). The channels are truncated to the shorter of the two, since a frame is only complete when both channels have a sample in it.

func IsSilence added in v0.1.0

func IsSilence(pcm []byte) bool

IsSilence reports whether a chunk of 16-bit signed PCM is silence, by comparing the largest absolute sample amplitude against speakingThreshold.

It expects clean speech or true silence: a stream with audible background noise keeps the amplitude above the threshold and never reads as silent. An empty buffer carries no audible sample and so counts as silence.

func MixAudio added in v0.1.0

func MixAudio(a, b []byte) []byte

MixAudio sums two streams of 16-bit signed PCM sample by sample, clipping the result to the 16-bit range. The streams need not be the same length: the shorter one is treated as though it were padded with silence, so the result is as long as the longer input.

func PCMToALaw added in v0.1.0

func PCMToALaw(pcm []byte, r *resample.Resampler) []byte

PCMToALaw converts 16-bit PCM to the rate r runs at and encodes it as G.711 A-law. A nil r leaves the rate alone. See ULawToPCM.

func PCMToULaw added in v0.1.0

func PCMToULaw(pcm []byte, r *resample.Resampler) []byte

PCMToULaw converts 16-bit PCM to the rate r runs at and encodes it as G.711 μ-law. A nil r leaves the rate alone. Resampling comes first, for the reason given on ULawToPCM.

func PCMToWAV added in v0.1.0

func PCMToWAV(pcm []byte, sampleRate, numChannels int) []byte

PCMToWAV wraps raw PCM in a WAV container. The samples are expected to be signed 16-bit little-endian, which is what pipelines carry, interleaved by channel.

Trailing bytes that do not complete a frame are dropped. Keeping them would leave the header reporting a frame count that excludes them while the data chunk still carries them, so readers would disagree about the length, and a stereo stream cut mid-frame would come back with its channels swapped.

func ResamplePCM added in v0.1.0

func ResamplePCM(pcm []byte, r *resample.Resampler) []byte

ResamplePCM converts 16-bit PCM to the rate r runs at, leaving the samples otherwise untouched. A nil r returns the audio unchanged. It is the companding-free member of the family above, for a stream that is already linear PCM and only needs its rate changed.

func ScaleAudio added in v0.4.0

func ScaleAudio(pcm []byte, factor float64) []byte

ScaleAudio scales the volume of a stream of 16-bit signed PCM by multiplying its samples by factor: 1.0 leaves the audio unchanged, 0.5 halves it. Each sample is scaled in single precision, clipped to the 16-bit range and truncated toward zero.

func ULawToPCM added in v0.1.0

func ULawToPCM(ulaw []byte, r *resample.Resampler) []byte

ULawToPCM decodes G.711 μ-law to 16-bit PCM and converts it to the rate r runs at. A nil r leaves the rate alone.

Decoding comes first: companded bytes are not samples, so resampling them would interpolate between values on a logarithmic scale as though they were linear.

Types

type Chain

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

Chain applies several Filters in sequence, composing multiple input-audio stages — noise reduction, gating, conditioning — into one Filter that a transport can use through Params.AudioInFilter.

func NewChain

func NewChain(filters ...Filter) *Chain

NewChain builds a Chain that applies filters in the given order.

func (*Chain) Filter

func (c *Chain) Filter(ctx context.Context, pcm []byte) ([]byte, error)

Filter runs pcm through each filter in order.

func (*Chain) ProcessFrame added in v0.1.0

func (c *Chain) ProcessFrame(ctx context.Context, f frames.FilterControlFrame) error

ProcessFrame applies a control frame to every filter, returning the last error if any. Each filter decides for itself which controls it recognizes.

func (*Chain) Start

func (c *Chain) Start(ctx context.Context, sampleRate int) error

Start starts every filter in order, stopping at the first error.

func (*Chain) Stop

func (c *Chain) Stop(ctx context.Context) error

Stop stops every filter, returning the last error if any.

type Filter

type Filter interface {
	Start(ctx context.Context, sampleRate int) error
	Stop(ctx context.Context) error
	Filter(ctx context.Context, pcm []byte) ([]byte, error)
	ProcessFrame(ctx context.Context, f frames.FilterControlFrame) error
}

Filter transforms input audio before it enters the pipeline. Start is called with the input sample rate when the transport starts, Filter is called for each received chunk of 16-bit mono PCM, and Stop is called when the transport stops. Filter may buffer internally and return fewer (or more) samples than it was given; it returns an empty slice when it has nothing to emit yet. ProcessFrame applies a runtime control frame, so the filter can be retuned or switched off without being torn down.

The pcm a filter is handed is read-only. The chunk it came in belongs to a frame, and a frame that has been pushed is being read elsewhere, so a filter that wrote into it would be writing under that reader. Return the filtered audio in a slice of the filter's own, or return the one it was given unchanged.

type Mixer

type Mixer interface {
	Start(ctx context.Context, sampleRate int) error
	Stop(ctx context.Context) error
	Mix(ctx context.Context, pcm []byte) ([]byte, error)
	ProcessFrame(ctx context.Context, f frames.MixerControlFrame) error
}

Mixer mixes auxiliary audio (background music or sound effects, say) into a transport's outgoing audio. Start is called with the output sample rate when the transport starts; Mix blends the mixer's current audio into an outgoing chunk of bot audio and returns the result; ProcessFrame applies a runtime control frame; Stop is called when the transport stops.

type SpeechSegmentBuffer added in v0.4.0

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

SpeechSegmentBuffer keeps the audio of one stretch of speech, with the audio just before it.

Between stretches of speech it keeps only the last PreSpeech of audio, which holds the start of the speech the VAD reports late. From Start to Stop it keeps everything, or the last Max of it, and Stop returns the segment. The audio is 16-bit mono PCM.

buffer := audio.NewSpeechSegmentBuffer(audio.DefaultPreSpeech, 0)
buffer.SetSampleRate(16000)

buffer.Append(pcm)        // every input audio chunk
buffer.Start()            // when the VAD reports speech
segment := buffer.Stop()  // when the VAD reports silence

It is not safe for concurrent use.

func NewSpeechSegmentBuffer added in v0.4.0

func NewSpeechSegmentBuffer(preSpeech, maxDuration time.Duration) *SpeechSegmentBuffer

NewSpeechSegmentBuffer builds a buffer keeping preSpeech of audio from before speech starts, and at most the last max of a segment; a max of zero keeps it all. Set the sample rate before appending audio.

func (*SpeechSegmentBuffer) Append added in v0.4.0

func (b *SpeechSegmentBuffer) Append(pcm []byte)

Append adds audio, dropping the oldest beyond what the buffer keeps.

func (*SpeechSegmentBuffer) SetSampleRate added in v0.4.0

func (b *SpeechSegmentBuffer) SetSampleRate(sampleRate int)

SetSampleRate sets the sample rate of the audio to come, in Hz.

func (*SpeechSegmentBuffer) Start added in v0.4.0

func (b *SpeechSegmentBuffer) Start()

Start starts a segment, with the audio kept from before it.

func (*SpeechSegmentBuffer) Stop added in v0.4.0

func (b *SpeechSegmentBuffer) Stop() []byte

Stop ends the segment and returns its audio, emptying the buffer.

Directories

Path Synopsis
Package dtmf generates the dual-tone multi-frequency signals a telephone keypad produces, as 16-bit mono PCM.
Package dtmf generates the dual-tone multi-frequency signals a telephone keypad produces, as 16-bit mono PCM.
Package g711 implements the ITU-T G.711 companding codecs used by telephony media streams (Twilio, Telnyx, Plivo and the wider PSTN): μ-law (PCMU), the North American variant, and A-law (PCMA), used elsewhere.
Package g711 implements the ITU-T G.711 companding codecs used by telephony media streams (Twilio, Telnyx, Plivo and the wider PSTN): μ-law (PCMU), the North American variant, and A-law (PCMA), used elsewhere.
Package loudness measures how loud audio is, to ITU-R BS.1770 (the EBU R128 standard), and normalizes the result to a 0..1 scale.
Package loudness measures how loud audio is, to ITU-R BS.1770 (the EBU R128 standard), and normalizes the result to a 0..1 scale.
Package mixer mixes background audio into a transport's outgoing audio.
Package mixer mixes background audio into a transport's outgoing audio.
noise
gate
Package gate provides a noise gate: an audio.Filter that silences a chunk of audio whose RMS energy falls below a threshold, suppressing low-level background hum and hiss between speech.
Package gate provides a noise gate: an audio.Filter that silences a chunk of audio whose RMS energy falls below a threshold, suppressing low-level background hum and hiss between speech.
rnnoise
Package rnnoise is an input audio filter that suppresses background noise with RNNoise, Xiph's recurrent-network denoiser.
Package rnnoise is an input audio filter that suppresses background noise with RNNoise, Xiph's recurrent-network denoiser.
Package onset detects the first audible sample in a stream of PCM audio.
Package onset detects the first audible sample in a stream of PCM audio.
Package opus wraps the Opus codec for jargo's audio path: it decodes Opus packets to PCM on the way in and encodes PCM to Opus packets on the way out.
Package opus wraps the Opus codec for jargo's audio path: it decodes Opus packets to PCM on the way in and encodes PCM to Opus packets on the way out.
Package resample converts interleaved S16LE PCM audio between sample rates, preserving the channel count.
Package resample converts interleaved S16LE PCM audio between sample rates, preserving the channel count.
Package turn provides end-of-turn detection: it decides when a user has actually finished speaking, as opposed to merely pausing.
Package turn provides end-of-turn detection: it decides when a user has actually finished speaking, as opposed to merely pausing.
vad
Package vad provides voice activity detection: it tells the pipeline when a user is speaking.
Package vad provides voice activity detection: it tells the pipeline when a user is speaking.
controller
Package controller drives a voice-activity detector and reports what it hears.
Package controller drives a voice-activity detector and reports what it hears.

Jump to

Keyboard shortcuts

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