본문 바로가기

Android/Guide

SoundPool 사용하기

긴 음악이 아닌 간단한 효과음을 내기 위해서 SoundPool 을 많이 사용한다.

 

사용법은 간단하다. SoundPool 을 선언하고, SDK 버전에 따라 빌더 또는 생성자를 이용하여 선언한다.

이 부분을 onCreate(), onStart() 에서 호출해주고, onStop()에서 릴리즈처리를 한다.

private SoundPool soundPool;

private void setSoundPool() {
    if (soundPool == null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();
            soundPool = new SoundPool.Builder().setAudioAttributes(audioAttributes).setMaxStreams(8).build();
        } else {
            // maxStream, streamType, quality
            soundPool = new SoundPool(8, AudioManager.STREAM_MUSIC, 0);
        }
    }
}

private void releaseSoundPool() {
    soundPool.release();
    soundPool = null;
}

간단한 효과음을 위한 ogg파일을 준비하고 아래처럼 음원을 load 한다. (요즘도 ogg 사용하는거 맞지?)

load() 후에 바로 play() 를 하면 재생되지 않는 경우가 있다. 그렇기에 onLoadComplete() 를 이용하여 처리하도록 한다.

private int soundResId;
private SoundPool soundPool;
private Context context;

public void playSound() {
    // context, resId, priority
    final int sound = soundPool.load(context, soundResId, 1);
    soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            // soundId, leftVolumn, rightVolumn, priority, loop, rate
            soundPool.play(sound, 1f, 1f, 0, 0, 1.0f);
        }
    });
}

 

SoundPool 의 단점은 플레이 도중과 끝을 알 수 없기에 컨트롤이 불가하다. MediaPlayer 에는 OnCompletionListener() 를 사용할 수 있는데 아쉬운 부분이다.

 

하지만 사람마음이 다 비슷하다보니 누군가가 이 둘을 적절히 섞어 컨트롤이 가능하게 만들어 제공하고 있다. 귿~

https://github.com/khliu1238/SoundPoolPlayer

 

khliu1238/SoundPoolPlayer

custom extention from SoundPool with setOnCompletionListener without the low-efficiency drawback of MediaPlayer - khliu1238/SoundPoolPlayer

github.com

사용법은 아래처럼 매우 간단하다. 당연히 pause, stop, resume, isPlaying 등의 MediaPlayer 기능을 그대로 사용할 수 있다.

SoundPoolPlayer

custom extention from Android SoundPool with setOnCompletionListener without the low-efficiency drawback of MediaPlayer.

SoundPoolPlayer mPlayer = SoundPoolPlayer.create(context, resId);
mPlayer.setOnCompletionListener(
	new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) { 	//mp will be null here
        	Log.d("debug", "completed");
        }
	};
);
mPlayer.play()