Updated Tutorial:Playing Sounds (markdown)

Gary 2017-10-23 21:55:16 -05:00
parent 7131513a8c
commit 242b3041f3

@ -1,19 +1,34 @@
# Overview
A game is made up of not just graphics, but also sounds. Typically you're going to want to play some sounds during the course of the game. Ebiten comes with built in functionality to play MP3, Ogg/Vorbis, WAV, and PCM files.
There are a couple of steps that need to be taken in order to integrate sound into your game:
1) Define an audio context with audio.NewContext. Only one audio context is required per program. The value passed to the audio context is the sample rate - 44100 or 48000 are fairly standard sample rates and should work in most places. Different values like 22050 may not work in some applications (ie: Safari)
1) Define an audio.Context with audio.NewContext. Only one audio context is required per program. The value passed to the audio context is the sample rate - 44100 or 48000 are fairly standard sample rates and should work in most places. Different values like 22050 may not work in some applications (ie: Safari)
`audioContext, err = audio.NewContext(sampleRate)`
2) Load in the file to be played using something like ebiten.OpenFile or os.Open()
'f, err := ebitenutil.OpenFile("_resources/audio/jab.wav")'
`f, err := ebitenutil.OpenFile("_resources/audio/jab.wav")`
3) Call the Decode() function associated with the media type. This will resample the audio to the same sample rate as the audioContext and will prevent garbled-sounding files.
'd, err := wav.Decode(audioContext, f)'
`d, err := wav.Decode(audioContext, f)`
4) Finally, create an audio player. This player will provide the interface for playing the sound during the course of the program.
4) Finally, create an audio.Player. This player will provide the interface for playing the sound during the course of the program.
'audioPlayer, err = audio.NewPlayer(audioContext, d)'
`audioPlayer, err = audio.NewPlayer(audioContext, d)`
# Playing Sounds
Once an audio context has been created and sounds have been loaded, playing the sound is as simple as:
1) Define something to trigger playing the sound (ie: check for a button press). Call audioPlayer.IsPlaying() to check if the sound is already playing. Unless you want some sort of reverb/garbled sound, you typically don't want to play the sound while it's already playing.
2) Call audioPlayer.Rewind() to seek the file to the very beginning
3) Call audioPlayer.Play() to start the sound!
4) Call audioContext.Update() somewhere in the function passed to ebiten.Run()
A complete example of playing a .wav sound can be [found here](https://github.com/hajimehoshi/ebiten/blob/master/examples/wav/main.go).