segmenter

package
v1.11.2 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 15 Imported by: 2 modules, 3 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.

README

Segmenter

The segmenter reads media files, and segments them into sections, each containing a contiguous block of speech, music, noise or silence. It can cut at a fixed duration, at silence, or near times you give it, and it classifies each segment.

It's designed for preparing audio for speech recognition and analysis: for example, splitting a podcast into parts at its pauses, sending each part to a transcriber, and skipping the music and silence between them.

import "github.com/mutablelogic/go-media/segmenter"

seg, err := segmenter.Open("podcast.mp3", 16000,
 segmenter.WithSegments(30*time.Second),
 segmenter.WithMode(segmenter.ModeVADAggressive, 0, 0),
)
if err != nil {
 return err
}
defer seg.Close()

err = seg.Decode(ctx, func(s *segmenter.Segment) error {
 fmt.Println(s.Start, s.Duration, s.Class, s.Stats.Speech)
 return nil
})

Open takes a file path or URL, and NewReader takes an io.Reader. The callback is called for each segment, in order, with segments which follow on from each other with no gaps. A segment's samples are only valid during the callback, so copy them to keep them. Return io.EOF from the callback to stop early.

Building

The segmenter uses cgo, and links FFmpeg and libfvad as static libraries, which the Makefile downloads and builds into build/install, with their pkg-config files. See the requirements for the tools you need to build them. Then:

make ffmpeg libfvad   # Build the libraries the segmenter needs
make test-libfvad     # Build them if needed, and run the segmenter tests
make cmd/segmenter    # Build the segmenter command, to build/segmenter

To run go build or go test yourself, set the same environment variables the Makefile does, so cgo finds the libraries:

export PKG_CONFIG_PATH="${PWD}/build/install/lib/pkgconfig"
export CGO_LDFLAGS_ALLOW="-(W|D).*"
export CGO_LDFLAGS="-lstdc++ -Wl,-no_warn_duplicate_libraries"  # drop the -Wl,... flag on Linux
go test ./segmenter

In another module which uses the segmenter, set PKG_CONFIG_PATH to the lib/pkgconfig folder of an installation with FFmpeg's libraries and libfvad.pc, such as this one's build/install.

Options

Option Description
WithSegments(d) Output a segment when it reaches the duration d (minimum 100ms)
WithSegments(t1, t2, ...) Cut segments near these times from the start, at least two seconds apart, preferring a silence within a second of each, so there's one segment for each part between them
WithMode(mode, silence, threshold) How silence is detected, and whether segments are classified (see below)
WithStream(index) The audio stream to decode. Without it, the audio stream with the lowest index is decoded
WithReaderOpt(opt) An option for the reader, such as reader.WithInput("s16le", "sample_rate=16000", "channels=1") for raw audio, or reader.WithInput("avfoundation") for a device

Modes

WithMode sets how silence is detected. Segments are cut where silence has lasted at least the silence duration, which is 500ms if it's zero.

Mode Silence is where Classification
ModeNone (default) Never Silence or unknown
ModeSilence The RMS energy is below threshold (0.01 if zero) Silence or unknown
ModeVADQuality, ModeVADLowBitrate, ModeVADAggressive, ModeVADVeryAggressive There's no speech, or the RMS energy is below threshold if it's set Silence, speech, music or other

The voice activity detection (VAD) modes use libfvad, the WebRTC voice activity detector, in increasing order of aggressiveness: a more aggressive mode is more likely to be right when it reports speech, but misses more of it. ModeVADAggressive is a good choice. They work at any sample rate, as the segmenter resamples a copy of the audio to 8000 Hz for the detector.

How segments are cut

  • At a fixed duration, with WithSegments(d).
  • At silence: when silence has lasted the silence duration, the segment before it is output straight away, without waiting for the silence to end. The silence is then output as a segment of its own, classified as silence, when sound starts again or it reaches the segment duration. A segment shorter than half the segment duration is output with the start of the silence after it, rather than on its own.
  • Near times you give, with WithSegments(t1, t2, ...). The audio is cut into pieces of at most a second, and at silences, and the pieces are joined together up to each time. Each cut is at the edge between two pieces which is nearest the time, preferring an edge next to silence within a second of it. So with silence detection, cuts are usually in a pause, and without it, they're within half a second of the time. Times after the end of the audio are ignored.

Classification

Each segment has a Class, and Stats which it was classified from:

Class Meaning
ClassSilence The segment was detected as silence, or its RMS energy is below the threshold
ClassSpeech Mostly speech
ClassMusic Music, or other sound with a slowly changing spectrum
ClassOther Other sound, such as noise
ClassUnknown Not silence, and not classified further, as the mode isn't a VAD mode

The voice activity detector alone reports most sounds as speech, including music, tones and noise, so the classification also uses features measured over 20ms frames. Speech has pauses between syllables and words, so many frames with low energy (LowEnergy), a zero-crossing rate which varies as voiced and unvoiced sounds alternate (ZCRVariation), and a spectrum which changes quickly (Flux). When background sound, such as in a news report from the field, fills the pauses, fewer frames have low energy, so a zero-crossing rate which varies a lot also counts as speech. Music has a spectrum which changes more slowly, and the detector reports it as speech (Speech). Everything else is other sound.

A segment is classified from at least the last six seconds of audio before its end (ClassifyWindow), including audio before the segment if it's shorter, so short segments are classified as reliably as long ones, without waiting for any audio after them. RMS and Peak are measured over the segment only, and the other stats over that window. Stats also includes features which aren't used for classification yet, such as Harmonicity, Rhythm and Centroid, to help tune it.

Accuracy

The thresholds were chosen from the MUSAN corpus of speech, music and noise, a music library and a news podcast. With ModeVADAggressive and two second segments, across all 109 hours of MUSAN:

Recording Speech Music Other Silence
Speech 86.2% 7.2% 2.2% 4.4%
Music 5.0% 83.3% 8.8% 2.9%
Noise 11.8% 23.3% 48.3% 16.6%

On a sample of 300 tracks from a personal music library, about 80% of the audio was classified as music, and on a 25 minute news podcast, about 98% was classified as speech.

Limitations
  • Loud, dense music, such as distorted rock, and sparse ambient music, are often classified as other sound.
  • A quarter of noise is classified as music, as much of it is harmonic or rhythmic, such as engines, sirens and machinery.
  • Speech over music is usually classified as music.
  • Music with sound effects, such as a cartoon soundtrack, can be classified as speech.
  • Just after a change, such as from music to speech, a short segment can be classified partly from the audio before it.

Real-time

The segmenter works on live sources, such as a stream or a device, as well as files, and adds little latency:

  • It processes audio about 450 times faster than real time on one core of a Mac Studio (Apple M4 Max), with a VAD mode.
  • A segment is output as soon as the silence after it has lasted the silence duration, or it reaches the segment duration. The voice activity detector takes about 120ms to notice that speech has ended.
  • Classification only uses audio before the end of a segment.
  • With WithSegments(t1, t2, ...), a segment is output when audio has arrived up to a second after its time, to look for a silence near it.
  • When the context passed to Decode is cancelled, such as to stop recording, the audio so far is output as the last segment.

To record from a microphone, open the device with its input format. On macOS, with AVFoundation, :0 is the first audio device with no video, and ffmpeg -f avfoundation -list_devices true -i "" lists them:

seg, err := segmenter.Open(":0", 16000,
	segmenter.WithReaderOpt(reader.WithInput("avfoundation")),
	segmenter.WithMode(segmenter.ModeVADAggressive, 0, 0.01),
)

With a VAD mode, a threshold such as 0.01 stops the background noise of a quiet room, which the detector sometimes reports as speech, from cutting the silence between speech into many short segments.

Testing

make test-libfvad   # Tests for sys/libfvad and the segmenter
make musan          # Download the MUSAN corpus (11GB) to build/musan
make test-musan     # Classify 50 files of each kind from MUSAN, and summarise
make test-musan MUSAN_LIMIT=0   # Classify all of MUSAN

The segmenter command

cmd/segmenter runs the segmenter from the command line, locally. segmenter segment prints the segments of a file or URL, and given a folder after it, writes each one to a file in the folder, encoded with --format (wav, mp3 or aac), so you can listen to them:

segmenter segment --segments 3m10s,7m45s --format mp3 podcast.mp3 parts
segmenter segment --mode silence --csv stats.csv podcast.mp3

segmenter stream shows the segments of a stream or a device, such as a microphone, as it plays, without writing anything. A device is device://<format>/<address>, and segmenter stream with no URL lists the audio input devices. On a terminal, it shows a meter of the level, and the class and stats of the last segment, below the segments as they're output. It stops at the end of the stream, after --duration, or when you press Ctrl-C. It only takes --mode, --silence, --threshold (0.01 by default, so background noise isn't taken for sound) and --duration:

segmenter stream device://avfoundation/:0

segmenter classify classifies folders of labelled audio, and summarises how each label was classified and how each feature is distributed. Each folder is named for its label, or given as label=folder. make test-musan runs it on MUSAN, writing the class and stats of each segment to build/musan.csv:

segmenter classify --limit 300 --csv music.csv music=/path/to/music

segment and classify take the same options as the package: --mode, --silence, --threshold, --segments, --rate and --stream, and --input-format and --input-opts for raw audio.

Documentation

Overview

Package segmenter provides audio segmentation functionality.

The segmenter reads audio from any supported format (using the reader package) and outputs segments of mono float32 samples at a chosen sample rate. It supports:

  • Fixed segment sizes (e.g., 30 seconds)
  • Silence-based segmentation (break on silence boundaries)
  • Sample rate conversion
  • Mono output (single channel)

Use cases include:

  • Speech-to-text preprocessing (splitting audio into segments)
  • Audio analysis (processing chunks at a time)
  • Streaming audio processing

Index

Constants

View Source
const (
	DefaultSilenceThreshold = 0.01                   // Default silence threshold (RMS)
	DefaultSilenceDuration  = time.Millisecond * 500 // Default silence duration
	MinSegmentDuration      = time.Millisecond * 100 // Minimum segment/silence duration
	MinBoundaryInterval     = 2 * boundaryTolerance  // Minimum time between the times to cut segments at
)
View Source
const ClassifyWindow = 6 * time.Second

ClassifyWindow is the minimum duration of samples a segment is classified with. A shorter segment is classified with the samples before it as well, so it isn't output any later.

View Source
const VADFrameDuration = 20 * time.Millisecond

VADFrameDuration is the duration of each frame of samples which is analysed for voice activity

Variables

This section is empty.

Functions

This section is empty.

Types

type Class

type Class int

Class is the kind of audio in a segment

const (
	ClassUnknown Class = iota // Not silence, and not classified further
	ClassSilence              // Silence
	ClassSpeech               // Mostly speech
	ClassMusic                // Tonal sound which isn't speech, such as music
	ClassOther                // Other sound, such as noise
)

Classes of audio. A segment is silence when its RMS energy is below the silence threshold, or DefaultSilenceThreshold when there's none. Otherwise, it's classified further only with a ModeVAD mode.

func (Class) String

func (c Class) String() string

type Mode

type Mode int

Mode sets how silence is detected, to break segments at silence boundaries

const (
	ModeNone              Mode = iota // No silence detection
	ModeSilence                       // Silence is where the RMS energy is below the threshold
	ModeVADQuality                    // Silence is where there's no speech, or the RMS energy is below the threshold
	ModeVADLowBitrate                 // See ModeVADQuality
	ModeVADAggressive                 // See ModeVADQuality
	ModeVADVeryAggressive             // See ModeVADQuality
)

Silence detection modes. The voice activity detection modes are in increasing order of aggressiveness: a more aggressive mode is more likely to be right when it reports speech, but misses more of it.

func (Mode) String

func (m Mode) String() string

type Opt

type Opt func(*opts) error

Opt is a function which applies options to a Segmenter

func WithMode

func WithMode(mode Mode, silence time.Duration, threshold float64) Opt

WithMode sets how silence is detected, to break segments where silence has lasted at least the silence duration (minimum 100ms, or zero for DefaultSilenceDuration). The threshold is the RMS energy level (0.0-1.0) below which audio is silence. With ModeSilence, zero is DefaultSilenceThreshold. With the voice activity detection modes, which also classify segments as speech, music or other sound, zero is no threshold.

func WithReaderOpt

func WithReaderOpt(opt reader.Opt) Opt

WithReaderOpt passes a reader.Opt to the reader, such as reader.WithInput to set the input format of raw audio.

func WithSegments

func WithSegments(v ...time.Duration) Opt

WithSegments sets how segments are cut. With one duration, it's the target segment duration, so segments are output when they reach approximately this duration (minimum 100ms). With more than one, they're the times from the start to cut segments at, in increasing order, not including the start or the end, at least MinBoundaryInterval apart. Each cut is at a silence within a second of the time if there is one, so one segment is output for each part of the audio between the times.

func WithStream

func WithStream(stream int) Opt

WithStream sets the index of the audio stream to decode. Without it, the audio stream with the lowest index is decoded.

type Segment

type Segment struct {
	Start    time.Duration // Timestamp of the first sample
	Duration time.Duration // Duration of the samples
	Samples  []float32     // Samples, in the range [-1.0, 1.0]
	Class    Class         // Kind of audio
	Stats    Stats         // Measurements of the samples
}

Segment is a segment of mono audio samples, passed to a SegmentFn. It's only valid during the call, as its samples are reused for the next one.

func (*Segment) Int16

func (s *Segment) Int16() []int16

Int16 returns a copy of the samples, in the range [-32767, 32767].

type SegmentFn

type SegmentFn func(*Segment) error

SegmentFn is called for each segment. Return nil to continue, io.EOF to stop early, or any other error to abort.

type Segmenter

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

Segmenter reads audio samples from a reader and segments them into chunks. It can be used to process audio samples in chunks for speech recognition, audio analysis, etc.

func NewReader

func NewReader(r io.Reader, sampleRate int, opts ...Opt) (*Segmenter, error)

NewReader creates a new segmenter from an io.Reader. See Open for parameter documentation.

func Open

func Open(url string, sampleRate int, opts ...Opt) (*Segmenter, error)

Open creates a new segmenter from a file path or URL. The sampleRate is the output sample rate in Hz (e.g., 16000 for speech). The output is always mono (single channel).

Options:

  • WithSegments(duration) - output segments of approximately this duration
  • WithSegments(time, time, ...) - output segments cut near these times
  • WithMode(mode, silence, threshold) - also break segments where silence has lasted at least the silence duration, detected by RMS energy (ModeSilence) or voice activity detection (ModeVAD...)
  • WithStream(index) - the audio stream to decode
  • WithReaderOpt(opt) - options for the reader

func (*Segmenter) Close

func (s *Segmenter) Close() error

Close releases all resources associated with the segmenter.

func (*Segmenter) Decode

func (s *Segmenter) Decode(ctx context.Context, fn SegmentFn) error

Decode decodes the audio stream into mono float32 samples at the configured sample rate, and calls fn for each segment. When the context is cancelled, such as to stop recording from a device, the samples so far are output as the last segment, and the context's error is returned.

func (*Segmenter) Duration

func (s *Segmenter) Duration() time.Duration

Duration returns the total duration of the media stream. Returns zero if duration is unknown.

func (*Segmenter) SampleRate

func (s *Segmenter) SampleRate() int

SampleRate returns the configured output sample rate.

func (*Segmenter) Stream

func (s *Segmenter) Stream() int

Stream returns the index of the audio stream which is decoded.

type Stats

type Stats struct {
	Speech        float64 // Fraction of frames with speech (0.0-1.0), with a ModeVAD mode
	RMS           float64 // RMS energy of the samples (0.0-1.0)
	Peak          float64 // Largest absolute sample value (0.0-1.0)
	Flatness      float64 // Mean spectral flatness, from tonal (0.0) to noise (1.0)
	ZCR           float64 // Mean zero-crossing rate, in crossings per sample
	ZCRVariation  float64 // Standard deviation of the zero-crossing rate, divided by its mean
	LowEnergy     float64 // Fraction of frames with less than half the mean RMS energy
	Modulation    float64 // Fraction of the energy's modulation at the syllable rate of speech (2-8Hz)
	Centroid      float64 // Mean spectral centroid, in Hz
	Flux          float64 // Mean spectral flux, how much the spectrum changes between frames (0.0-2.0)
	FluxVariation float64 // Standard deviation of the spectral flux, divided by its mean
	Rhythm        float64 // Strength of a steady beat of 60-180 BPM in the energy onsets (0.0-1.0)
	Harmonicity   float64 // Mean harmonicity, from noise (0.0) to a periodic sound with a pitch of 100-1000Hz (1.0)
	Voiced        float64 // Fraction of frames with a harmonicity of at least 0.5
}

Stats are measurements of a segment's samples. Except for RMS and Peak, they're measured over 20ms frames

Jump to

Keyboard shortcuts

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