google / oboe

Oboe is a C++ library that makes it easy to build high-performance audio apps on Android.
Apache License 2.0
3.7k stars 566 forks source link

How to deal with sound effects? #147

Closed ghost closed 6 years ago

ghost commented 6 years ago

How can I play a sound effects when the last playback was not finished? For example, the percussion effect of a rhythm game, an audio can be play many times at the same time.

dturner commented 6 years ago

This is up to you. There are 2 options:

1) Have many instances of a percussion sound (with a set maximum of say 10 concurrent sounds) and trigger each one independently. You would need to play each sound through a mixer.

2) Have a single instance of the percussion sound and restart it each time the user taps the drum.

It really depends on what kind of effect you want to achieve. Option 2 is more common for a single drum since this is actually what happens in the real world. You can bang a drum many times but you still only have one drum.

ghost commented 6 years ago

Thanks for your prompt reply. What I need is the Option 1. Does the same audio's wave data occupy the same memory in multiple instances?

dturner commented 6 years ago

So for option 1 you would need multiple sound objects, each with its own separate memory.

You could use the SoundRecording and Mixer objects from here: https://github.com/google/oboe/tree/master/samples/RhythmGame/src/main/cpp/audio

Each SoundRecording could be initialized using the same sound asset which copies the contents into memory using SoundRecording::loadFromAsset. Each SoundRecording could be added to the Mixer using addTrack.

On each audio callback you would call Mixer::renderAudio. On each tap you would need to switch on the next sound which isn't currently playing by calling SoundRecording::setPlaying(true). The easiest way to do this is probably to just loop through the array of sounds and play the first one where isPlaying returns false (method is trivial to implement).

ghost commented 6 years ago

Thanks a lot.