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.

79 lines
1.7 KiB

  1. // Package sdl implements an audio engine using libSDL2.
  2. package sdl
  3. import "github.com/veandco/go-sdl2/mix"
  4. // Engine is the SDL2 audio engine.
  5. type Engine struct {
  6. initFlags int
  7. }
  8. // New initializes an SDL2 Mixer for the audio engine.
  9. //
  10. // Pass the SDL2 Mixer flags for its initialization. The flags are an OR'd
  11. // value made up of:
  12. // mix.INIT_MP3
  13. // mix.INIT_OGG
  14. // mix.INIT_FLAC
  15. // mix.INIT_MOD
  16. func New(flags int) (*Engine, error) {
  17. return &Engine{
  18. initFlags: flags,
  19. }, nil
  20. }
  21. // Setup initializes SDL2 Mixer.
  22. func (e *Engine) Setup() error {
  23. // Initialize SDL2 mixer.
  24. if err := mix.Init(e.initFlags); err != nil {
  25. return err
  26. }
  27. // Open the audio mixer.
  28. // the '2' is stereo (two channels), '1' would be mono.
  29. // 4096 is the chunk size.
  30. // https://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_11.html
  31. return mix.OpenAudio(mix.DEFAULT_FREQUENCY, mix.DEFAULT_FORMAT, 2, 4096)
  32. }
  33. // Playing returns if either music or sounds are currently playing.
  34. func (e *Engine) Playing() bool {
  35. if mix.PlayingMusic() {
  36. return true
  37. }
  38. return mix.Playing(-1) > 0
  39. }
  40. // PlayingMusic returns if music is currently playing.
  41. func (e *Engine) PlayingMusic() bool {
  42. return mix.PlayingMusic()
  43. }
  44. // PlayingSound returns if sounds are playing.
  45. func (e *Engine) PlayingSound() bool {
  46. return mix.Playing(-1) > 0
  47. }
  48. // StopAll stops all music and sounds.
  49. func (e *Engine) StopAll() {
  50. e.StopMusic()
  51. e.StopSounds()
  52. }
  53. // StopMusic stops all music.
  54. func (e *Engine) StopMusic() {
  55. mix.HaltMusic()
  56. }
  57. // StopSounds stops all sounds.
  58. func (e *Engine) StopSounds() {
  59. mix.HaltChannel(-1)
  60. }
  61. // Teardown closes the SDL mixer.
  62. func (e *Engine) Teardown() error {
  63. mix.CloseAudio()
  64. mix.Quit()
  65. return nil
  66. }