Files
beatglow/_old/audio/time.go
T
2026-10-29 17:29:41 +01:00

61 lines
1.1 KiB
Go

package audio
import (
"fmt"
"strconv"
"time"
)
// Rate is the sampling rate.
type Rate int
// Frequency is the sampling frequency.
func (r Rate) Frequency() Frequency {
return 1 / Frequency(r)
}
// Duration of n samples at this rate.
func (r Rate) Duration(n int) time.Duration {
return time.Second * time.Duration(n) / time.Duration(r)
}
// Number of sample during duration d.
func (r Rate) Samples(d time.Duration) int {
return int(d * time.Duration(r) / time.Second)
}
func (r Rate) String() string {
return strconv.FormatInt(int64(r), 10)
}
// Frequency is a type alias for float64.
type Frequency float64
const (
Hz Frequency = 1
KHz Frequency = 1e3
MHz Frequency = 1e6
GHz Frequency = 1e9
THz Frequency = 1e12
)
func (f Frequency) String() string {
switch {
case f > THz:
return fmt.Sprintf("%gTHz", f/THz)
case f > GHz:
return fmt.Sprintf("%gGHz", f/GHz)
case f > MHz:
return fmt.Sprintf("%gMHz", f/MHz)
case f > KHz:
return fmt.Sprintf("%gkHz", f/KHz)
default:
return fmt.Sprintf("%gHz", f)
}
}
// Rate is the sampling rate for this frequency.
func (r Frequency) Rate() Rate {
return Rate(1 / r)
}