Loading Sounds

The next thing to do with your SoundPool is to load it up with sounds. The main benefit of using a SoundPool over some other methods of playing audio is that SoundPool responds quickly: When you tell it to play a sound, it will play the sound immediately, with no lag.

The trade-off for that is that you must load sounds into your SoundPool before you play them. Each sound you load will get its own integer ID. To track this ID, add an mSoundId field to Sound and a generated getter and setter to keep track of it.

Listing 21.2  Adding sound ID field (Sound.java)

public class Sound {
    private String mAssetPath;
    private String mName;
    private Integer mSoundId;
    ...
    public String getName() {
        return mName;
    }

    public Integer getSoundId() {
        return mSoundId;
    }

    public void setSoundId(Integer soundId) {
        mSoundId = soundId;
    }
}

By making mSoundId an Integer instead of an int, you make it possible to say that a Sound has no value set for mSoundId by assigning it a null value.

Now to load your sounds. Add a load(Sound) method to BeatBox to load a Sound into your SoundPool.

Listing 21.3  Loading sounds into SoundPool (BeatBox.java)

    private void loadSounds() {
        ...
    }

    private void load(Sound sound) throws IOException {
        AssetFileDescriptor afd = mAssets.openFd(sound.getAssetPath());
        int soundId = mSoundPool.load(afd, 1);
        sound.setSoundId(soundId);
    }

    public List<Sound> getSounds() {
        return mSounds;
    }
}

Calling mSoundPool.load(AssetFileDescriptor, int) loads a file into your SoundPool for later playback. To keep track of the sound and play it back again (or unload it), mSoundPool.load(…) returns an int ID, which you stash in the mSoundId field you just defined. And since calling openFd(String) throws IOException, load(Sound) throws IOException, too.

Now load up all your sounds by calling load(Sound) inside BeatBox.loadSounds().

Listing 21.4  Loading up all your sounds (BeatBox.java)

private void loadSounds() {
    ...
    for (String filename : soundNames) {
        try {
            String assetPath = SOUNDS_FOLDER + "/" + filename;
            Sound sound = new Sound(assetPath);
            load(sound);
            mSounds.add(sound);
        } catch (IOException ioe) {
            Log.e(TAG, "Could not load sound " + filename, ioe);
        }
    }
}

Run BeatBox to make sure that all the sounds loaded correctly. If they did not, you will see red exception logs in Logcat.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.129.100