No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

reencode.go 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package cmd
  2. import (
  3. "bufio"
  4. "io"
  5. "log"
  6. "os"
  7. "github.com/BakeRolls/wave"
  8. "github.com/spf13/cobra"
  9. )
  10. var reencodeCmd = &cobra.Command{
  11. Use: "reencode [in] [out]",
  12. Short: "Read a WAV file and reencode it into another file, but it writes the average over the surrounding 100 samples",
  13. Args: cobra.ExactArgs(2),
  14. Run: func(cmd *cobra.Command, args []string) {
  15. r, err := os.Open(args[0])
  16. if err != nil {
  17. log.Fatal(err)
  18. }
  19. defer r.Close()
  20. br := bufio.NewReaderSize(r, 1024)
  21. wavr, err := wave.NewReader(br)
  22. if err != nil {
  23. log.Fatal(err)
  24. }
  25. w, err := os.Create(args[1])
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. defer w.Close()
  30. wavw, err := wave.NewWriter(w, wavr.Config())
  31. if err != nil {
  32. log.Fatal(err)
  33. }
  34. defer wavw.Close()
  35. samples := make([]int16, 100)
  36. for {
  37. sample, err := wavr.Read16()
  38. if err != nil {
  39. if err == io.EOF {
  40. break
  41. }
  42. log.Fatal(err)
  43. }
  44. samples = append(samples[1:], sample)
  45. if err := wavw.Write16(average(samples)); err != nil {
  46. log.Fatal(err)
  47. }
  48. }
  49. },
  50. }
  51. func average(is []int16) int16 {
  52. var avg float64
  53. for _, i := range is {
  54. avg += float64(i)
  55. }
  56. return int16(avg / float64(len(is)))
  57. }
  58. func init() {
  59. rootCmd.AddCommand(reencodeCmd)
  60. }