Skip to content

Instantly share code, notes, and snippets.

@unixpickle
Created July 10, 2021 18:41
Show Gist options
  • Save unixpickle/60aea80737c2e8f68f8bde8a1b96171e to your computer and use it in GitHub Desktop.
Save unixpickle/60aea80737c2e8f68f8bde8a1b96171e to your computer and use it in GitHub Desktop.
Split audio files into constant-length chunks
package main
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"github.com/unixpickle/essentials"
"github.com/unixpickle/ffmpego"
)
const (
SampleRate = 16000
ChunkSize = SampleRate * 15
ChunkMin = SampleRate * 4
)
func main() {
if len(os.Args) < 3 {
fmt.Fprintln(os.Stderr, "Usage: splitaudio <input> [input ...] <output dir>")
os.Exit(1)
}
inputs := os.Args[1 : len(os.Args)-1]
outputDir := os.Args[len(os.Args)-1]
chunkIdx := 0
for _, file := range inputs {
log.Println("Splitting up", file)
SplitFile(file, outputDir, &chunkIdx)
}
}
func SplitFile(path, outputDir string, chunkIdx *int) {
ar, err := ffmpego.NewAudioReaderResampled(path, SampleRate)
essentials.Must(err)
defer ar.Close()
for {
chunk := make([]float64, ChunkSize)
n, err := ar.ReadSamples(chunk)
if n > ChunkMin {
*chunkIdx += 1
name := fmt.Sprintf("chunk_%06d.flac", *chunkIdx)
aw, err := ffmpego.NewAudioWriter(filepath.Join(outputDir, name), SampleRate)
essentials.Must(err)
essentials.Must(aw.WriteSamples(chunk))
aw.Close()
}
if err == io.EOF {
break
}
essentials.Must(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment