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

54 lines
1.1 KiB
Go

package transcode
import (
"os"
"github.com/go-audio/audio"
"github.com/go-audio/wav"
)
func writePCM16WAV(path string, sampleRate int, channels int, samples []float64) error {
if channels <= 0 {
channels = 1
}
if err := os.MkdirAll(dirOf(path), 0o755); err != nil && dirOf(path) != "." {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
enc := wav.NewEncoder(f, sampleRate, 16, channels, 1)
data := make([]int, len(samples))
for i, s := range samples {
data[i] = floatToInt16(s)
}
if err := enc.Write(&audio.IntBuffer{
Format: &audio.Format{SampleRate: sampleRate, NumChannels: channels},
Data: data,
}); err != nil {
return err
}
return enc.Close()
}
func floatToInt16(f float64) int {
if f > 1 {
f = 1
}
if f < -1 {
f = -1
}
return int(f * 32767)
}
func dirOf(path string) string {
for i := len(path) - 1; i >= 0; i-- {
if path[i] == '/' || path[i] == '\\' {
return path[:i]
}
}
return "."
}