开发者

NullPointerException when trying to play a sound with MediaPlayer

开发者 https://www.devze.com 2023-04-09 05:44 出处:网络
So I have a simple soundboard type application that operates via a ListView. Tap an item, it plays the sound. I have a public static int[] named soundResourceList that has entries such as R.raw.foo, R

So I have a simple soundboard type application that operates via a ListView. Tap an item, it plays the sound. I have a public static int[] named soundResourceList that has entries such as R.raw.foo, R.raw.bar in the same order of the entries associated with the text in the ListView.

This code has worked for many users including myself, however one re开发者_JAVA百科cently posted a NullPointerException, in particularly from the setOnCompletionListener line. This to me means that MediaPlayer.create returned null, but I can't figure out why it would fail on their device but not everybody else's.

public void onListItemClick(ListView parent, View v, int position, long id) {
    MediaPlayer mp = MediaPlayer.create(getBaseContext(), soundResourceList[position]);
    mp.setOnCompletionListener(new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            mp.release();
        }
    });
    mp.setOnPreparedListener(new OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
}

Normally a NPE with MediaPlayer is due to something like not releasing its previous instance, but I already have that issue handled as shown in the code. So what am I missing that might cause the MediaPlayer.create() to fail?


The create method doc says:

Returns
    a MediaPlayer object, or null if creation failed

Since a number of low-level resources might be allocated for each MediaPlayer, it could be that if the GC is busy for a while or doesn't run you'll run out of sound buffers (or whatever) and the MediaPlayer allocation will fail, returning null.

If these are all relatively-short-lived audio snippets, you might look into android.media.SoundPool.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号