sounds

package
v0.23.5 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 19 Imported by: 1 module, 1 package

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 sounds is the family's cue sounds: a catalogue of sounds an app ships (catalog.json and the audio files, read from an fs.FS the app passes in: actnowkit carries no audio), the choice of a sound for each of the app's events (a sound of the catalogue, a macOS system sound, or none), filtering by group, tag and text for a picker, and a player with low latency for quick repeats (AVAudioPlayer on macOS through purego; a silent output elsewhere).

cat, err := sounds.Load(appResources, "sounds")     // sounds/catalog.json
player := sounds.NewPlayer(cat, nil)                 // nil: the platform's output
ev := sounds.Event{ID: "record.start", Default: "tally", Fallback: "Pop"}
player.Preload(prefs.Choice(ev))
player.PlayEvent(ev, prefs)                          // the user's choice, at their volume
player.Preview("chime", prefs.Volume)                // the picker's ▶, cutting off the last preview

The family's catalogue lives in a private repository (the sounds are licensed for use inside apps, not for redistribution on their own); apps copy it into their bundles. A build without it (a source build of an open source app) passes a nil catalogue: every event then plays its Fallback system sound.

Index

Constants

View Source
const (
	None         = "none"
	SystemPrefix = "system:"
)

A choice is what a setting holds for an event:

""             the event's default
"none"         no sound
"system:Ping"  a macOS system sound by name (NSSound's names)
"chime"        a sound of the catalogue
View Source
const CatalogFile = "catalog.json"

CatalogFile is the catalogue's file name in its directory.

View Source
const DefaultVolume = 70

DefaultVolume is a fresh install's volume: cues should not compete with the user's own audio.

View Source
const EngineRate = 44100

EngineRate is the rate DecodeWAV converts to (the family's sounds are 44.1 kHz already).

View Source
const Schema = "actnow.sounds.catalog/1"

Schema is the schema of catalog.json.

View Source
const SystemSoundsDir = "/System/Library/Sounds"

SystemSoundsDir is the folder of macOS's system sounds.

View Source
const UnknownLength = 800 * time.Millisecond

UnknownLength is how long a preview of a sound of unknown length (a system sound not measured) is taken to play.

Variables

View Source
var (
	ErrNoCatalog = errors.New("sounds: no catalogue")
	ErrUnknown   = errors.New("sounds: unknown sound")
)

Errors.

View Source
var KnownSystemSounds = []string{"Basso", "Blow", "Bottle", "Frog", "Funk", "Glass", "Hero", "Morse", "Ping", "Pop", "Purr", "Sosumi", "Submarine", "Tink"}

KnownSystemSounds are the sounds macOS 15–26 ships in /System/Library/Sounds.

View Source
var VolumeSteps = []int{0, 25, 50, 75, 100}

VolumeSteps are the volumes a picker offers (its volume button's list, loudest first in the pop-up).

Functions

func IsKnownSystem

func IsKnownSystem(name string) bool

IsKnownSystem reports whether name is one of KnownSystemSounds.

func IsSystem

func IsSystem(choice string) bool

IsSystem reports whether choice names a system sound.

func MigrateClosest

func MigrateClosest(cat *Catalog, name string) string

MigrateClosest is the catalogue's closest sound to the system sound name (Catalog.ForSystem), or System(name) when none replaces it.

func MigrateSystem

func MigrateSystem(ev Event, name string, wasDefault bool) string

MigrateSystem is the choice for a setting that named the macOS system sound name before the family's sounds: when the user had left it on the app's old default (wasDefault), the event's new default; otherwise the system sound itself, kept as the user chose it. An empty name is the event's default.

func NearestVolumeStep added in v0.9.1

func NearestVolumeStep(v int) int

NearestVolumeStep is the step of VolumeSteps closest to v (the one a picker shows as chosen for a volume set before the steps).

func System

func System(name string) string

System is the choice of the macOS system sound name.

func SystemName

func SystemName(choice string) string

SystemName is the system sound a choice names ("" for other choices).

func SystemSounds

func SystemSounds(dir string) []string

SystemSounds lists the sounds in dir ("" = SystemSoundsDir) by name ("Pop" for Pop.aiff), sorted, without repeats; nil when dir cannot be read (off macOS).

func ToneWAV

func ToneWAV(freq, seconds, gain float64) []byte

ToneWAV is a 16-bit mono WAV of a sine at freq Hz for seconds at gain (0–1), with 5 ms fades: a test sound that needs no catalogue.

func VolumeLevel added in v0.9.1

func VolumeLevel(v int) int

VolumeLevel is how a volume is drawn: 0 muted, 1 low (up to 50 %), 2 high.

Types

type Catalog

type Catalog struct {
	Schema  string  `json:"schema"`
	Version string  `json:"version"`
	Groups  []Group `json:"groups"`
	Tags    []Tag   `json:"tags,omitempty"`
	Uses    []Use   `json:"uses,omitempty"`
	Sounds  []Sound `json:"sounds"`
	// Notice is the attribution the app shows (About, acknowledgements).
	Notice string `json:"notice,omitempty"`
	// contains filtered or unexported fields
}

Catalog is a catalogue of sounds and where to read their files.

func Load

func Load(fsys fs.FS, dir string) (*Catalog, error)

Load reads dir/catalog.json from fsys (dir "" or "." for the root) and checks it: the schema, unique ids, known groups, files inside dir. Missing files are found when a sound is read (Data).

func Parse

func Parse(b []byte, fsys fs.FS, dir string) (*Catalog, error)

Parse reads a catalogue from b; its files are read from fsys under dir.

func (*Catalog) Check

func (c *Catalog) Check() []error

Check reads every sound's file and returns the problems (missing files, SHA-256 mismatches): for an app's tests of its bundled copy.

func (*Catalog) Data

func (c *Catalog) Data(id string) ([]byte, error)

Data reads the sound's file (once; later calls share the bytes, which callers must not change) and checks its SHA-256 when the catalogue gives one.

func (*Catalog) Filter

func (c *Catalog) Filter(f Filter) []Sound

Filter lists the sounds that pass f, in catalogue order.

func (*Catalog) ForSystem

func (c *Catalog) ForSystem(name string) string

ForSystem is the sound that replaces the macOS system sound name (Sound.Replaces), for migrating settings; "" when none does.

func (*Catalog) Group

func (c *Catalog) Group(id string) (Group, bool)

Group returns the group id.

func (*Catalog) GroupCounts

func (c *Catalog) GroupCounts(f Filter) []GroupCount

GroupCounts lists the groups with how many sounds of each pass f (ignoring its group), in catalogue order; groups with none are left out.

func (*Catalog) GroupName added in v0.9.1

func (c *Catalog) GroupName(id, lang string) string

GroupName is the group's name in lang (the id for a group the catalogue does not describe).

func (*Catalog) JSON

func (c *Catalog) JSON() ([]byte, error)

JSON is the catalogue as catalog.json.

func (*Catalog) Match

func (c *Catalog) Match(s Sound, f Filter) bool

Match reports whether s passes f. The query matches, word by word, the sound's id, names, description, tags and group (case-insensitive).

func (*Catalog) Sound

func (c *Catalog) Sound(id string) (Sound, bool)

Sound returns the sound id. A nil catalogue has none.

func (*Catalog) Subset

func (c *Catalog) Subset(keep func(Sound) bool) *Catalog

Subset is a catalogue of the sounds keep reports true for, with the groups that still have sounds (an app that ships some of the family's sounds builds its catalog.json this way: WriteJSON).

func (*Catalog) Suggested

func (c *Catalog) Suggested(ev Event) []Sound

Suggested lists the sounds that suit ev (its Uses), its default first.

func (*Catalog) TagCounts

func (c *Catalog) TagCounts(f Filter, featuredOnly bool) []TagCount

TagCounts lists the tags of the sounds that pass f without its own tags (the chips a picker can still offer), featured tags first and then by count, each with how many of those sounds carry it. featuredOnly keeps the catalogue's featured tags alone.

func (*Catalog) TagName

func (c *Catalog) TagName(id, lang string) string

TagName is the tag's name in lang (the id itself for a tag the catalogue does not describe).

func (*Catalog) UseName

func (c *Catalog) UseName(id, lang string) string

UseName is the use's name in lang (the id for one not described).

type Event

type Event struct {
	ID   string
	Name Text
	// Default is the choice of a fresh install: a sound of the catalogue
	// (or None for an event that is off until the user picks a sound).
	Default string
	// Fallback is the system sound played for a catalogue sound that
	// this build does not have (no catalogue: a source build without the
	// family's sounds): "Pop". "" = silence.
	Fallback string
	// Uses are the catalogue's uses that suit the event: the picker
	// suggests their sounds first.
	Uses []string
}

Event is something an app plays a sound for ("record.start", "pick", "poke"). Apps declare their events; the user's choices are Prefs.

type Filter

type Filter struct {
	Group string
	Tags  []string
	Query string
	Uses  []string
}

Filter is what a picker shows: a group ("" = all), tags the sounds must all carry, a text to search for, and uses (any of them; for "suggested").

func (*Filter) ToggleTag

func (f *Filter) ToggleTag(tag string)

ToggleTag adds tag to f.Tags, or takes it out when present.

type Group

type Group struct {
	ID   string `json:"id"`
	Name Text   `json:"name"`
}

Group is a group of sounds (a picker's section).

type GroupCount

type GroupCount struct {
	Group
	Count int
}

GroupCount is a group and how many sounds pass a filter in it.

type Kind

type Kind int

Kind is what a resolved choice plays.

const (
	KindNone    Kind = iota // nothing
	KindCatalog             // a sound of the catalogue
	KindSystem              // a macOS system sound
)

type Output

type Output interface {
	// Load prepares sound data (a WAV, CAF … file's bytes) under key, so
	// that Play starts it at once. Loading a key again is a no-op.
	Load(key string, data []byte) error
	// Play starts the sound loaded under key at volume (0–1) and returns
	// at once. Quick repeats overlap rather than cut each other off.
	Play(key string, volume float64) (Voice, error)
	// PlaySystem starts the macOS system sound name ("Pop").
	PlaySystem(name string, volume float64) (Voice, error)
}

Output plays sounds: the platform's (DefaultOutput: AVAudioPlayer and NSSound on macOS, silence elsewhere) or a test's (Recorder).

func DefaultOutput

func DefaultOutput() Output

DefaultOutput is the platform's output: Silent off macOS.

type PCM

type PCM struct {
	Rate        int
	Left, Right []float32
}

PCM is decoded audio: two channels of float32 samples at Rate.

func DecodeWAV

func DecodeWAV(b []byte) (p PCM, ok bool)

DecodeWAV decodes a RIFF WAVE file (PCM 8/16/24/32-bit or IEEE float 32-bit, mono or more channels: the first two are kept, mono is doubled) to stereo float32 at EngineRate (linear interpolation when the file's rate differs). ok is false for anything else (the caller plays the bytes some other way).

type Player

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

Player plays the sounds of a catalogue (nil: none, every event plays its fallback) on an Output. It is safe for concurrent use; Play and its kin return at once, but the first play of a sound reads and decodes it (Preload does that ahead).

func NewPlayer

func NewPlayer(cat *Catalog, out Output) *Player

NewPlayer is a player of cat on out (nil: DefaultOutput()).

func (*Player) Catalog

func (p *Player) Catalog() *Catalog

Catalog is the player's catalogue (nil when the build has none).

func (*Player) Play

func (p *Player) Play(t Target) (Voice, error)

Play plays t; nothing for KindNone.

func (*Player) PlayEvent

func (p *Player) PlayEvent(ev Event, prefs Prefs) (Target, error)

PlayEvent plays what ev plays with prefs (nothing while they are off) and returns what that was.

func (*Player) Preload

func (p *Player) Preload(choices ...string) error

Preload loads the catalogue sounds among choices (others are skipped), so that their first play starts at once. It returns the first error.

func (*Player) Preview

func (p *Player) Preview(choice, fallback string, volume int) (Target, error)

Preview plays choice for a picker at volume (percent), stopping the preview before it: ▶ on a row, "Test" on an event (pass the event's choice and Fallback). Choosing None stops the last preview and plays nothing.

func (*Player) Previewing added in v0.9.1

func (p *Player) Previewing() (choice string, left time.Duration)

Previewing is the choice the last preview plays and how long it has left; "" when none plays: a picker's ▶ shows its state (and redraws after left).

func (*Player) SetClock added in v0.9.1

func (p *Player) SetClock(now func() time.Time)

SetClock replaces the player's clock (tests of Previewing).

func (*Player) StopPreview

func (p *Player) StopPreview()

StopPreview stops the last preview if it still plays.

type Prefs

type Prefs struct {
	On     bool              `json:"on"`
	Volume int               `json:"volume"` // percent, 0–100
	Events map[string]string `json:"events,omitempty"`
}

Prefs are an app's sound settings: on or off, volume, and a choice per event (only those that differ from the event's default are kept). Apps keep it in their own settings file; it is not shared with the family.

func DefaultPrefs

func DefaultPrefs() Prefs

DefaultPrefs are a fresh install's prefs: on, at DefaultVolume, every event on its default.

func (Prefs) Choice

func (p Prefs) Choice(ev Event) string

Choice is the choice for ev: the user's, or ev.Default.

func (*Prefs) Choose

func (p *Prefs) Choose(ev Event, choice string)

Choose sets the choice for ev; choosing its default removes the entry.

func (*Prefs) Normalize

func (p *Prefs) Normalize()

Normalize clamps the volume and drops choices that are malformed.

func (Prefs) Target

func (p Prefs) Target(cat *Catalog, ev Event) Target

Target is what ev plays with these prefs (nothing while they are off).

type Recorder

type Recorder struct {

	// Err, when set, is returned by Load, Play and PlaySystem.
	Err error
	// contains filtered or unexported fields
}

Recorder is an Output for tests: it records what was loaded and played ("chime@0.7", "system:Pop@0.5", and "stop chime" for a stopped voice).

func (*Recorder) Load

func (r *Recorder) Load(key string, data []byte) error

func (*Recorder) Loaded

func (r *Recorder) Loaded() []string

Loaded lists the keys loaded, in order.

func (*Recorder) Play

func (r *Recorder) Play(key string, volume float64) (Voice, error)

func (*Recorder) PlaySystem

func (r *Recorder) PlaySystem(name string, volume float64) (Voice, error)

func (*Recorder) Played

func (r *Recorder) Played() []string

Played lists what was played and stopped, in order.

func (*Recorder) Reset

func (r *Recorder) Reset()

Reset forgets what was recorded.

type Silent

type Silent struct{}

Silent is an Output that plays nothing (DefaultOutput off macOS).

func (Silent) Load

func (Silent) Load(string, []byte) error

func (Silent) Play

func (Silent) Play(string, float64) (Voice, error)

func (Silent) PlaySystem

func (Silent) PlaySystem(string, float64) (Voice, error)

type Sound

type Sound struct {
	ID    string   `json:"id"`
	File  string   `json:"file"` // relative to the catalogue's directory
	Name  Text     `json:"name"`
	Group string   `json:"group"`
	Tags  []string `json:"tags,omitempty"`
	// Duration is how long the file plays, in seconds.
	Duration float64 `json:"duration"`
	// Audible is how long it is heard (to its last sample above −60 dBFS),
	// in seconds; 0 = Duration. An app that waits for a cue to end (a
	// start-of-recording cue before muting the output) waits this long.
	Audible float64  `json:"audible,omitempty"`
	Desc    Text     `json:"desc,omitzero"`
	Uses    []string `json:"uses,omitempty"`
	// Pair is the sound that goes with this one (a start cue's stop cue,
	// a switch's on and off).
	Pair string `json:"pair,omitempty"`
	// Replaces lists macOS system sounds ("Pop", "Tink") this sound is the
	// closest to: a setting that named one migrates to this sound.
	Replaces []string `json:"replaces,omitempty"`
	SHA256   string   `json:"sha256,omitempty"` // of File
	Source   *Source  `json:"source,omitempty"`
}

Sound is one sound of the catalogue.

func (Sound) HasTag

func (s Sound) HasTag(tag string) bool

HasTag reports whether the sound carries tag.

func (Sound) Length

func (s Sound) Length() time.Duration

Length is the sound's audible length (Audible, or Duration).

type Source

type Source struct {
	Name     string `json:"name"`               // "React Bits Sound Lab"
	ID       string `json:"id,omitempty"`       // the source's id of the sound
	Title    string `json:"title,omitempty"`    // the source's name of the sound
	Exported string `json:"exported,omitempty"` // date of the export, 2006-01-02
	SHA256   string `json:"sha256,omitempty"`   // of the exported file, before processing
}

Source says where a sound comes from.

type Tag

type Tag struct {
	ID   string `json:"id"`
	Name Text   `json:"name"`
	// Featured tags are the picker's filter chips; the others still match
	// a text search.
	Featured bool `json:"featured,omitempty"`
}

Tag is a label sounds carry, for filtering ("soft", "bright", "short" …).

type TagCount

type TagCount struct {
	Tag
	Count int
}

TagCount is a tag and how many sounds carry it.

type Target

type Target struct {
	Kind   Kind
	Name   string
	Volume float64
}

Target is what an event plays: the kind, the sound's id or system name, and the volume (0–1).

func Resolve

func Resolve(cat *Catalog, choice, fallback string, volume int) Target

Resolve is what choice plays with cat (nil: no catalogue): a catalogue sound it has, a system sound, or fallback (a system sound name) for a catalogue sound it lacks.

func (Target) Length

func (t Target) Length(cat *Catalog) time.Duration

Length is how long a target is heard: the catalogue sound's audible length, the system sound's (0 for one not measured), 0 for none.

type Text

type Text struct {
	En string `json:"en"`
	Zh string `json:"zh,omitempty"`
}

Text is a name in the interface languages.

func (Text) In

func (t Text) In(lang string) string

In is the text in lang (a BCP-47 tag: "zh", "zh-Hans", "zh-CN" … pick Chinese, anything else English); English when there is no translation.

type Use

type Use struct {
	ID   string `json:"id"`
	Name Text   `json:"name"`
}

Use is a suggested use of sounds ("record.start", "success", "poke" …): an app's events name the uses they suit, and the picker offers those sounds first.

type Voice

type Voice interface {
	// Stop ends the sound now; one that ended is left alone.
	Stop()
}

Voice is a sound that plays.

Jump to

Keyboard shortcuts

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