SuperGNESTM
SNES Emulator for Android Phones

We have sound on Android CupCake

Playing PCM Audio with a DataBuffer seams to be been an issue with a great deal of emulator and game developers for the Android platform. Having spent some time on this we thought it would be a good idea to share what we have learned.

As of the latest released version of Android ( CupCake ), the API contains an class called AudioTrack(). This class allows users to stream local buffered PCM audio directly to the audio hardware. In previous releases stream output was only available while reading from a FILE or a URL.

Here is an example of playing a PCM file. You can find the yes_08k.pcm file in the Android sources in /external/srec/tests/pcm

public void onCreate(Bundle savedInstanceState) {
    byte[] byteData;
    super.onCreate(savedInstanceState);

    try {
        // Open the file and load the entire file into a byte array
        File oFile = new File( "/sdcard/yes_08k.pcm");
        byteData = new byte[(int) oFile.length()];
        FileInputStream in = new FileInputStream( oFile );
        in.read( byteData );
        in.close(); 

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    int intSize = android.media.AudioTrack.getMinBufferSize(8000,
                                                            AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                                            AudioFormat.ENCODING_PCM_16BIT);

    AudioTrack oTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
                                       AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                       AudioFormat.ENCODING_PCM_16BIT, intSize,
                                       AudioTrack.MODE_STREAM);

    // Start playing data that is written
    oTrack.play();

    // Write the byte array to the track
    oTrack.write(byteData, 0, byteData.length);

    // Done writting to the track
    oTrack.stop();
}

If you have a WAV file and your not sure of the Hz or Bit rate use the ‘file‘ UNIX command. Most WAV files are just PCM with a small header and should also work with the above example with a small bit of sound corruption at the beginning as the WAV header is read in as PCM data.

$ file yes.wav
yes.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 8000 Hz

I hope this encourages people! We will have sound on Android CupCake!

Leave a Reply