go-whisper-api/api/waveform.go
admin b5c083e06f
Some checks failed
CodeQL / Analyze (go) (push) Successful in 6m28s
Docker Image / build-docker (push) Failing after 13m26s
Lint and Testing / lint (push) Successful in 11m17s
Lint and Testing / test (push) Successful in 11m17s
Lint and Testing / golangci (push) Successful in 2m40s
first commit
2026-06-04 18:10:52 +07:00

49 lines
1.0 KiB
Go

package api
import (
"math"
"os"
"github.com/go-audio/wav"
)
func waveformFromWav(path string, buckets int) ([]float64, error) {
if buckets <= 0 {
buckets = 256
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
dec := wav.NewDecoder(f)
buf, err := dec.FullPCMBuffer()
if err != nil {
return nil, err
}
samples := buf.AsFloat32Buffer().Data
if len(samples) == 0 {
return make([]float64, buckets), nil
}
chunk := len(samples) / buckets
if chunk < 1 {
chunk = 1
}
out := make([]float64, 0, buckets)
for i := 0; i < len(samples) && len(out) < buckets; i += chunk {
end := i + chunk
if end > len(samples) {
end = len(samples)
}
peak := 0.0
for _, s := range samples[i:end] {
v := math.Abs(float64(s))
if v > peak {
peak = v
}
}
out = append(out, math.Round(peak*1000)/1000)
}
return out, nil
}