A simple audio engine for Go with an SDL2 back-end and others to come eventually.
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.

119 lines
2.2 KiB

  1. // Example program using the SDL2 Mix engine.
  2. //
  3. // Plays a music or sound file from disk.
  4. // Usage: `play <filepath>`
  5. package main
  6. import (
  7. "flag"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path/filepath"
  12. "time"
  13. "git.kirsle.net/go/audio/sdl"
  14. "github.com/veandco/go-sdl2/mix"
  15. )
  16. // CLI flags.
  17. var (
  18. flagBinary bool
  19. flagLoop int
  20. )
  21. func init() {
  22. flag.BoolVar(&flagBinary, "binary", false,
  23. "Feed the file as bytes instead of by filename on disk.")
  24. flag.IntVar(&flagLoop, "loop", 0, "Number of times to loop the audio.")
  25. }
  26. func main() {
  27. flag.Parse()
  28. if len(os.Args) < 2 {
  29. fmt.Println("Usage: play <path/to/file.mp3>")
  30. fmt.Println("Supports .ogg, .mp3, .wav")
  31. os.Exit(1)
  32. }
  33. sfx, err := sdl.New(mix.INIT_MP3 | mix.INIT_OGG)
  34. if err != nil {
  35. panic(err)
  36. }
  37. sfx.Setup()
  38. var (
  39. filename = os.Args[len(os.Args)-1]
  40. sound sdl.Track
  41. )
  42. if flagBinary {
  43. fmt.Printf("Opening '%s' and feeding to engine as binary\n", filename)
  44. sound = loadBinary(sfx, filename)
  45. } else {
  46. fmt.Printf("Playing '%s' from filesystem\n", filename)
  47. sound = loadFilename(sfx, filename)
  48. }
  49. fmt.Printf("Begin playback")
  50. sound.Play(flagLoop)
  51. for sfx.Playing() {
  52. time.Sleep(1 * time.Second)
  53. fmt.Print(".")
  54. }
  55. fmt.Println("Done.")
  56. }
  57. func loadFilename(sfx *sdl.Engine, filename string) sdl.Track {
  58. var (
  59. sound sdl.Track
  60. err error
  61. )
  62. switch filepath.Ext(filename) {
  63. case ".ogg", ".mp3":
  64. sound, err = sfx.LoadMusic(filename)
  65. if err != nil {
  66. panic(err)
  67. }
  68. case ".wav":
  69. sound, err = sfx.LoadSound(filename)
  70. if err != nil {
  71. panic(err)
  72. }
  73. default:
  74. panic("Unsupported file type")
  75. }
  76. return sound
  77. }
  78. // Loads the audio file by sending the byte stream into the audio engine
  79. // instead of having the audio engine open it from filesystem itself.
  80. func loadBinary(sfx *sdl.Engine, filename string) sdl.Track {
  81. bin, err := ioutil.ReadFile(filename)
  82. if err != nil {
  83. panic(err)
  84. }
  85. var sound sdl.Track
  86. switch filepath.Ext(filename) {
  87. case ".ogg", ".mp3":
  88. sound, err = sfx.LoadMusicBin(bin)
  89. if err != nil {
  90. panic(err)
  91. }
  92. case ".wav":
  93. sound, err = sfx.LoadSoundBin(bin)
  94. if err != nil {
  95. panic(err)
  96. }
  97. default:
  98. panic("Unsupported file type: " + filepath.Ext(filename))
  99. }
  100. return sound
  101. }