Game Development Reference
In-Depth Information
Tip Using the MediaTrack API provides audio format independence. Whatever the format of your
sound file, Android will detect it and call the right driver for it (as long as the format is supported
by the platform). Moreover, it works in all versions of Android, thus giving you the widest range of
device support.
The process works as follows:
Consider a class dubbed NativeAudio that drives the audio playback
with a static method start . Within start , you create a Java thread
that contains an instance of the Android MediaTrack API.
1.
2.
MediaTrack can be used to play audio by declaring an instance of
an audio track with a set of user-defined audio parameters. In this
case, you want to stream (hence AudioManager.STREAM_MUSIC) at a
frequency of 22kHz using two channels ( STEREO ) with a buffer size of
4 * (22050 / 5).
mTrack = new AudioTrack(
android.media.AudioManager.STREAM_MUSIC,
22050,
AudioFormat.CHANNEL_CONFIGURATION_STEREO, // stereo
AudioFormat.ENCODING_PCM_16BIT, // 16 bit audio
4 * (22050 / 5), // Buffer size
AudioTrack.MODE_STREAM);
3.
When the thread starts, it enters a loop continuously reading
from the C engine using the native function Natives.
PaintAudio(audioBuffer) . The process continues until the loop
is told to stop using a boolean variable. In that case, the thread
terminates and the audio track is disposed, as shown in Listing 6-5.
Listing 6-5. Playing Native Audio Using Android's MediaTrack
public class NativeAudio {
public static void start() {
mStarted = true;
new Thread(new Runnable() {
public void run() {
// Android Audio API
AudioTrack mTrack;
 
Search WWH ::




Custom Search