안드로이드 APP에 사운드를 추가해보자.
- new SoundPool( 5, AudioManager.STREAM_MUSIC, 0 );로 SoundPool 객체를 만든다.
- AudioManager 상수 중 STREAM_MUSIC은 일반적으로 사용하며 게임 쪽에 유효하다.
- AudioManager 상수는 특성이 조금씩 다르다.
- 예로 STREAM_NOTIFICATION, STREAM_RING, ... 등 몇가지가 더 있는데 STREAM_NOTIFICATION을 사용하면 소리크기를 조정할 수 없다.
- SoundPool 클래스 설명
- http://developer.android.com/reference/android/media/SoundPool.html
- load( int maxStreams, int streamType, int srcQuality )메소드
- maxStreams 한 번에 재생가능 스트림 수
- streamType; STREAM_NOTIFICATION, STREAM_RING, STREAM_MUSIC, ....
- srcQuality; 0을 사용하면 무리 없이 작동한다.
- 아래는 원문을 발췌했다.
- maxStreams the maximum number of simultaneous streams for this SoundPool object
- streamType the audio stream type as described in AudioManager For example, game applications will normally use STREAM_MUSIC.
- srcQuality the sample-rate converter quality. Currently has no effect. Use 0 for the default.
Sound 클레스를 만들었다.
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
public class Sound {
private SoundPool sound_pool;
private int sound_beep;
Sound() {}
Sound(Context context, int iSoundFile)
{
sound_pool = new SoundPool( 5, AudioManager.STREAM_MUSIC, 0 );
sound_beep = sound_pool.load( context, iSoundFile, 1 );
}
public void initSound(Context context, int iSoundFile)
{
sound_pool = new SoundPool( 5, AudioManager.STREAM_MUSIC, 0 );
sound_beep = sound_pool.load( context, iSoundFile, 1 );
}
public void playSound()
{
sound_pool.play( sound_beep, 1f, 1f, 0, 0, 1f );
}
// initSound()와 playSound()를 하나로 합침
public void init_playSound(Context context, int iSoundFile)
{
sound_pool = new SoundPool( 5, AudioManager.STREAM_MUSIC, 0 );
sound_beep = sound_pool.load( context, iSoundFile, 1 );
sound_pool.play( sound_beep, 1f, 1f, 0, 0, 1f );
}
}
[사용 법]
- res폴더 하위에 raw폴더를 만들고 btn_main_level_default_click08.wav 사운드 파일을 넣는다.
- Sound객체를 만듦.
- Sound sndButtonStart;
- sndButtonStart = new Sound(this, R.raw.btn_main_level_default_click08);
- Sound(Context context, int iSoundFile) 생성자나 initSound(Context context, int iSoundFile) 메소드로 초기화를 한다.
- context는 사운드를 최종 호출해서 소리를 재생할 Activity클래스 객체다.
- iSoundFile는 R.java에서 참조하는 파일이다.
- R.raw.btn_main_level_default_click08 를 넣었다.
- 사운드를 재생할 줄에서 재생 매소드를 호출
- sndButtonStart.playSound();
- 주의:
- 사운드 폴더는 보통 res하위에 raw를 사용한다.
- raw폴더에 soundtest.wa파일을 넣었으면 soundtest.mp3, soundtest.ogg는 사용할 수 없다. 즉 확장자가 다르더라도 파일명이 같으면 않된다.
- 리소스 파일 아래에 넣어놓는 파일은 소문자와 언더바'_' 만이 유효하다. 재생이 안되거나 예기치 못한 에러를 접하게 된다.
'Android 안드로이드' 카테고리의 다른 글
안드로이드 앱에 AdMob 광고 달기 ][ (0) | 2014.08.02 |
---|---|
안드로이드 앱에 AdMob 광고 달기 (0) | 2014.08.02 |
FILL_PARENT와 MATCH_PARENT 는 무엇이 다를까? (0) | 2014.07.28 |
Component (0) | 2014.07.27 |
Intent 활용 예제 Activity 하나만 열어본다 (0) | 2014.07.27 |