search
LoginSignup
36

More than 5 years have passed since last update.

posted at

【Android】ロリポップからのSoundPool

今までSoundPoolのインスタンス化は下記のような方法でした。

final int SOUND_POOL_MAX = 6;

SoundPool pool = new SoundPool(SOUND_POOL_MAX, AudioManager.STREAM_MUSIC, 0);

Android 5.0 ロリポップ (API Level 21) からこの方法は非推奨になり、次の様な書き方が推奨されます。

final int SOUND_POOL_MAX = 6;

AudioAttributes attr = new AudioAttributes.Builder()
    .setUsage(AudioAttributes.USAGE_MEDIA)
    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
    .build();

SoundPool pool = new SoundPool.Builder()
    .setAudioAttributes(attr)
    .setMaxStreams(SOUND_POOL_MAX)
    .build();

互換性を保つ場合は下記の様な感じになると思います。

@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private SoundPool buildSoundPool(int poolMax)
{
    SoundPool pool = null;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        pool = new SoundPool(poolMax, AudioManager.STREAM_MUSIC, 0);
    }
    else {
        AudioAttributes attr = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build();

        pool = new SoundPool.Builder()
            .setAudioAttributes(attr)
            .setMaxStreams(poolMax)
            .build();
    }

    return pool;
}

final int SOUND_POOL_MAX = 6;
SoundPool pool = buildSoundPool(SOUND_POOL_MAX);

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
What you can do with signing up
36