LoginSignup
11

More than 5 years have passed since last update.

Android5.0でのSoundPoolバグ対策

Posted at

Android5.0でSoundPoolを使うと恐ろしいほど起動が遅くなることがあります。

Threadを使って回避する方法が手っ取り早かったが
バックグラウンドから復帰後にしばらくカクつく現象がおきたので他の方法を試してみた。

改善策

Android5.0だと6件目以降のロードに時間がかかるようなので
SoundPoolを配列化して1つのSoundPoolにつき6件以下のロードとなるようにすることで
動作に支障が出ない程度にパフォーマンスを出すことができました。

サンプルコード

HogeActivity.java
private final int MAX_STREAM = 5;
protected List<SoundPool> mSoundPools;
/** SoundPoolでロードした時のID */
protected int[] mSoundIds;
/** ロード対象のリソースID */
protected int[] mResouceIds; // R.javaで定義された再生対象のID入れてください

@Override
protected void onResume() {
    super.onResume();

    mSoundPools = new ArrayList<SoundPool>();
    mSoundIds = new int[mResouceIds.length];
    SoundPool soundPool = null;
    for (int i = 0; i < mResouceIds.length; i++) {
        if (i % MAX_STREAM == 0) {
        soundPool = new SoundPool(MAX_STREAM, AudioManager.STREAM_MUSIC, 0);
            mSoundPools.add(soundPool);
        }
        mSoundIds[i] = soundPool.load(getApplicationContext(), mResouceIds[i], 1);
    }
}

@Override
protected void onPause() {
    for (int i = 0; i < mSoundPools.size(); i++) {
        mSoundPools.get(i).realse();
    }
    mSoundPools = null;

    super.onPause();
}

public void soundPlay(int soundId) {
    SoundPool soundPool = mSoundPools.get(soundId / MAX_STREAM);
    soundPool.play(mResources[soundId], 1.0f, 1.0f, 0, 0, 1.0f);
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11