마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

main activity에서 sound 부분만 빼서 따로 클래스를 정의 했는데 오류가 생깁니다.

0 추천
public class SoundControl extends Activity{

 public static final int BASE = 1;
 public static final int ACTION = 2;
 public static final int GEAR = 3;

 private static final int BASE_SOUND = 10;
 SoundPool base_sound = null;
 SoundPool action_sound = null;
 SoundPool gear_sound = null;

 private AudioManager audio;

 int baseId;
 int actionId;
 int gearId;

 public void soundCreate( int id) {
  
  Context context = new SoundRacerActivity();

  switch (id) {
  case BASE:
   base_sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
   baseId = base_sound.load(context, R.raw.porsche_911_gt3_rs_basics2,
     1);
   audio.setStreamVolume(AudioManager.STREAM_MUSIC, BASE_SOUND, 0);
   break;
  case ACTION:
   action_sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
   actionId = action_sound.load(context,
     R.raw.porsche_911_gt3_rs_exhaust1, 1);
   break;

  case GEAR:
   gear_sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
   gearId = gear_sound.load(context,
     R.raw.porsche_911_gt3_rs_shift_gears, 1);
   break;
  }

 }

 public void play(int id) {
  switch (id) {
  case BASE:
   base_sound.play(baseId, 1.0f, 1.0f, 0, -1, 1.0f);
   break;
   
  case ACTION:
   action_sound.play(actionId, 1.0f, 1.0f, 0, -1, 1.0f);
   break;

  case GEAR:
   gear_sound.play(gearId, 1.0f, 1.0f, 0, -1, 1.0f);
   break;
  }
 }

 public void pause(int id) {
  switch (id) {
  case BASE:
   base_sound.pause(baseId);
   break;
  case ACTION:
   action_sound.pause(actionId);
   break;

  case GEAR:
   gear_sound.pause(gearId);
   break;
  }
 }

 public void release(int id) {

  switch (id) {
  case BASE:
   base_sound.stop(baseId);
   base_sound.release();
   base_sound = null;
   break;
  case ACTION:
   action_sound.stop(actionId);
   action_sound.release();
   action_sound = null;
   break;
  case GEAR:
   gear_sound.stop(gearId);
   gear_sound.release();
   gear_sound = null;
  }
 }

 public void audioInitial() {
  audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  audio.setStreamVolume(AudioManager.STREAM_MUSIC, BASE_SOUND, 0);
 }


 public void audioVolumeControl(int vol) {
  
  audio.setStreamVolume(AudioManager.STREAM_MUSIC, vol, 0);

 }

 public void stop() {
  if (action_sound != null) {
   action_sound.stop(actionId);
   action_sound.release();
   action_sound = null;
  } else if (base_sound != null) {
   base_sound.stop(baseId);
   base_sound.release();
   base_sound = null;
  } else {
   gear_sound.stop(gearId);
   gear_sound.release();
   gear_sound = null;
  }

 }

소스가 워낙 지저분 해서 sound 부분만 따로 빼서 main activity에서 사용하려고 합니다. 그런데 계속 오류가 나는데...이렇게 소스를 짜도 괜찮은가요??

안왕초보 (1,390 포인트) 님이 2014년 3월 5일 질문
안될건없는것 같은뎅
어디서 무슨 오류가 나나요?
음?! 밑에 분 답변보니.. 설마..... 라는 생각이드네요 ㅎㅎ
뭐가 메인액티비티에요?
일단 보이는 게 사운트 컨트롤이 클래스인지 액티비티인지...
public class SoundControl extends Activity{
액티비티를 상속했는데 생명주기는 없으니 클래스로 만들려고 하신거 같은데 @_@ 오잉잉..
activity 상속을 안하려고 하는데 getSystemService 쪽에 계속 오류가 생겨서 어쩔 수 없이 상속을 해버린거에요 ㅜㅜ
initail 부분은 그냥 main acitivity 쪽에 넣어버렸어요 흠..그런데

public void soundCreate( int id) {
   
  Context context = new SoundRacerActivity();
이 쪽에서 오류가 발생 해버리네요...아놔....
흠.... 밑에 분 답변대로 액티비티를 그렇게 클래스처럼 생성하시면 안되구요 ㅎㅎ 현재 보이는 SoundControl 클래스를 메인액티비티에서 new로 생성해주고 사용하시는거죠? 그럼 생성자함수에 인자로 Context context 를 넣어주세요 그다음에 context.getSystemService 를 하시면 될 것 같은데 '-'

요런식으로 추가하고
public SoundControl (Context context)
{
    super(context);
}
메인에서 생성할때는 이런식으로?

new SoundControl (getBaseContext());
activity 상속을 없애버렸어요 ㅎㅎ
일단 앱 실행은 되고 사운드 시작 모드로 들어가니 오류가 나네요 흠...그리고 super(context) 에러가...ㅜㅜ
context 부분이 어렵네요 ㅜㅜ
그럼 컨텍스트 전역 선언하고
Context c;

public SoundControl(Context context){
  // 슈퍼 대신 요런식으로 쓰면되지않을까요?
  c = context;
}
아 그 방법 생각 못했네요 ㅎㅎ
그런데 계속
public void soundCreate(int id) {
        Context context = new SoundRacerActivity();
이부분이 문제 발생 하네요...아..context 이해를 못하것네요....
이부분을
public void soundCreate(Context context, int id) {
이렇게 하고 main acitivity에서
soundControl.soundCreate(SoundRacerActivity.this , SoundControl.BASE); 이렇게 사용 해도 오류가 나고 어떤 씩으로 사용 해야 될지 아직 이해가 안되요...ㅜㅜ
컹.. 몇번이나 말씀드렸는데.. 밑에 분 답변을 보세요! ㅋㅋ
SoundRacerActivity(); 이늠이 액티비티이면 안된다구요
어떻게 사용하려고 하시는지 감이 잘 안오네용..
뭔가 아주 간단하게라도 순서도 같은게 있으면 편하겟는뎅
main activity에요 흠...Context c를 어떻게 사용 해야 될지...
Context context = new SoundRacerActivity();

아까 생성자에서 context 를 받아오는데 저걸 할 필요가 있는가용?
없애고 쓰시면 될거같은데
메인에서 SoundControl 을 생성할때 컨텍스트를 넘겨주니까요
public class SoundControl {

    public static final int BASE = 1;
    public static final int ACTION = 2;
    public static final int GEAR = 3;

    private static final int BASE_SOUND = 10;
    SoundPool base_sound = null;
    SoundPool action_sound = null;
    SoundPool gear_sound = null;

    private AudioManager audio;

    int baseId;
    int actionId;
    int gearId;
   
    Context c;
   
    public SoundControl (Context context)
     {
         c = context;
     }

    public void soundCreate(int id) {
       
        Context context = c;
        switch (id) {
        case BASE:
            base_sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
            baseId = base_sound.load(context, R.raw.porsche_911_gt3_rs_basics2,
                    1);
            audio.setStreamVolume(AudioManager.STREAM_MUSIC, BASE_SOUND, 0);
            break;
        case ACTION:
            action_sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
            actionId = action_sound.load(context,
                    R.raw.porsche_911_gt3_rs_exhaust1, 1);
            break;

        case GEAR:
            gear_sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
            gearId = gear_sound.load(context,
                    R.raw.porsche_911_gt3_rs_shift_gears, 1);
            break;
        }

    }

이렇게 해봤는데...여전히 오류가 흠...soundCreate 부분 Context 생성안하고 바로 Context c를 load 부분에 넣어도 오류가 발생 하고 있습니다..흠........ㅜㅜ 클래스 생성 안하고 바로 넣으면 되는데 나중에 사운드 더 붙이면 너무 지저분 해질 것 같아서 이렇게 하는데 아...지저분 해도 그냥 main에 넣어 버릴까 생각과 실력을 올리기 위해서는 이런 부분을 해결 해야 된다는 마음이 혼잡하네요 ㅜㅜ
컴파일 오류에요? 아니면 실행 시 오류에요?

p.s
soundCreate 안에는 굳이 컨텍스트를 재선언 안하셔도 context 인자 위치에 c 를 넣어주시면 되요
실행 오류입니다...쩝 context 생성 안하고 c를 넣어도 실행 오류가 ㅜㅜ
일단 main 입니다..

SoundControl soundControl = new SoundControl(getBaseContext());
를 전역 변수로 두고

public void onClick(View v) {
        Intent serverIntent = new Intent(this, DeviceListActivity.class);
        switch (v.getId()) {
        case R.id.btButton:
            if (initialized == false) {
                // Attempt to disconnect from the device

                startActivityForResult(serverIntent,
                        REQUEST_CONNECT_DEVICE_SECURE);
                soundControl.soundCreate(SoundControl.BASE);

            } else {
                // Attempt to connect to the device
                offOBD();
                mChatService.stop();
                soundControl.stop();
                // dataStorage();
                rpmText.setText("0");

            }
            break;

이부분은 블루투스 패어링 디바이스 선택 부분과 종료 부분입니다..패어링 디바이서 선택을 sound를 생성하려고 합니다...
저~ 위에 댓글소스 한번 테스트해봤는데
이늠 빼니까 실행 오류는 안나네요.
audio.setStreamVolume(AudioManager.STREAM_MUSIC, BASE_SOUND, 0);

컨텍스트는 클래스 내부에 전역으로 선언하셨으면 참조가 되는게 맞는뎅.. 왜 안되시는거징.. 흠
실행 오류는 오디오 매니저 때문이네요 ㅎㅎ

public class SoundControl {

    public static final int BASE = 1;
    public static final int ACTION = 2;
    public static final int GEAR = 3;

    private static final int BASE_SOUND = 10;
    SoundPool base_sound = null;
    SoundPool action_sound = null;
    SoundPool gear_sound = null;

    private AudioManager audio;

    int baseId;
    int actionId;
    int gearId;
    
    Context c;
    
    public SoundControl (Context context)
     {
        Log.i("생성자 호출", "실행됨" +context);
         c = context;
         audio = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
     }

    public void soundCreate(int id) {
        
        switch (id) {
        case BASE:
            Log.i("Base", "실행됨" +id);

            base_sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
            baseId = base_sound.load(c, R.raw.bird, 1);
            
            audio.setStreamVolume(AudioManager.STREAM_MUSIC, BASE_SOUND, 0);
            Log.i("Base", "44444444" +id);
            break;
        case ACTION:
            Log.i("ACTION", "실행됨" +id);
            action_sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
            actionId = action_sound.load(c, R.raw.bird, 1);
            Log.i("ACTION", "종료됨" +id);
            break;

        case GEAR:
            Log.i("GEAR", "실행됨" +id);
            gear_sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
            gearId = gear_sound.load(c, R.raw.bird, 1);
            Log.i("GEAR", "종료됨" +id);
            break;
        }

    }
}
오!!! 매번 감사합니다 ㅜㅜ
초보개발자님께서 가르쳐 주신 방법으로 계속 하는데 실행 오류가 생겨서 왜 그러는지 계속 소스 변화 시켰는데
SoundControl soundControl = new SoundControl(getBaseContext());
이부분을 전역 변수로 하면 안되고 main에 onCreate 부분에 넣으지 잘 되네요 ㅎㅎ 감사합니다
축하드려요~!! 매번 고생이 많으시네요 ㅋㅋ

1개의 답변

+1 추천
SoundRacerActivity 가 Activity를 상속받은 클래스라면 잘못쓰고 계신 겁니다.

Activity 클래스 객체는 직접 생성하면 안됩니다.
익명사용자 님이 2014년 3월 5일 답변
activity 상속을 안하려고 하는데 getSystemService 쪽에 계속 오류가 생겨서 어쩔 수 없이 상속을 해버린거에요 ㅜㅜ
getSystemService 오류 때문에 audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  audio.setStreamVolume(AudioManager.STREAM_MUSIC, BASE_SOUND, 0);
는 main activity 쪽으로 넣어버렸어요
...