'버튼 눌림 소리 효과'에 해당되는 글 1건

  1. 2014.07.28 안드로이드 앱에 사운드 효과 주기
Android 안드로이드2014. 7. 28. 09:34


안드로이드 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 )메소드
      1. maxStreams 한 번에 재생가능 스트림 수
      2. streamType; STREAM_NOTIFICATION, STREAM_RING, STREAM_MUSIC, ....
      3. srcQuality; 0을 사용하면 무리 없이 작동한다.
      4. 아래는 원문을 발췌했다.
      • 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 );

}

}



[사용 법]

  1. res폴더 하위에 raw폴더를 만들고 btn_main_level_default_click08.wav 사운드 파일을 넣는다.

  1. Sound객체를 만듦.
    1. Sound sndButtonStart;
    2. sndButtonStart = new Sound(this, R.raw.btn_main_level_default_click08);

      1. Sound(Context context, int iSoundFile) 생성자나 initSound(Context context, int iSoundFile) 메소드로 초기화를 한다. 
        • context는 사운드를 최종 호출해서 소리를 재생할 Activity클래스 객체다. 
        • iSoundFile는 R.java에서 참조하는 파일이다.
        • R.raw.btn_main_level_default_click08 를 넣었다.


  1. 사운드를 재생할 줄에서 재생 매소드를 호출
    1. sndButtonStart.playSound();


  2. 주의:
  3. 사운드 폴더는 보통 res하위에 raw를 사용한다.
  4. raw폴더에 soundtest.wa파일을 넣었으면 soundtest.mp3, soundtest.ogg는 사용할 수 없다. 즉 확장자가 다르더라도 파일명이 같으면 않된다.
  5. 리소스 파일 아래에 넣어놓는 파일은 소문자와 언더바'_' 만이 유효하다. 재생이 안되거나 예기치 못한 에러를 접하게 된다.


Posted by 코드버무려