2013-04-07 1 views
0

런타임 중에 단추를 만들고 싶습니다. 버튼을 누를 때 버튼이 소리를 내며 버튼을 누르는 것을 멈 추면 소리는 멈추어야합니다.런타임 중에 단추를 Action_Down 및 _up에 대한 onTouch 이벤트를 추가하여 단추를 누르는 동안 소리를 재생합니다.

웹 브라우징 및 스택 오버플로이 코드와 함께 제공 :

// Create a new button and place it into a table row 
    LinearLayout lnr = (LinearLayout) findViewById(R.id.tableRow3); 
    Button b1 = new Button(this); 
    lnr.addView(b1); 

    // Associate the event 
    b1.setOnTouchListener(new OnTouchListener() { 
     MediaPlayer mp = new MediaPlayer(); 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      switch(event.getAction() & MotionEvent.ACTION_MASK) { 
      case MotionEvent.ACTION_DOWN: 
       // Finger started pressing --> play sound in loop mode 
       try { 
        FileInputStream fileInputStream = new FileInputStream(PATH); 
        mp.setDataSource(fileInputStream.getFD()); 
        mp.prepare(); 
        mp.setLooping(true); 
        mp.start(); 
       } catch (Exception e) {} 
      case MotionEvent.ACTION_UP: 
       // Finger released --> stop playback 
       try { 
        mp.stop(); 
       } catch (Exception e) {} 
      } 
      return true; 
     } 
     }); 

문제는 내가 모든 소리를들을 수 없다는 것입니다. case MotionEvent.ACTION_UP:이 직접 트리거 된 것 같습니다. 따라서 재생이 직접 중지됩니다.

이 가설을 테스트하기 위해 나는 mp.stop();을 제거하고 소리의 무한 루프를 들었습니다. 모든 것을 망쳐 놓은 ACTION_UP 이벤트 여야합니다. 하지만 손가락/마우스를 놓지 않으면 어떻게 ACTION_UP 이벤트가 트리거 될 수 있습니까?

답변

2

''을 'case MotionEvent.ACTION_DOWN'하단에 삽입해야합니다.

+0

은 물론 ... 내가 MediaPlayer를 객체 또는 내가 명백한 놓친 MotionEvent에 문제가 발견 너무 염려했다. 감사합니다. 코드를 수정하고 아래에 첨부했습니다. –

+0

방금 ​​한 번만 작동한다는 것을 알았습니다. 버튼을 클릭하고 사운드 루프를 들었습니다. 단추를 놓으면 재생이 즉시 중단됩니다. 또한 mp.reset()을 추가해야합니다. mp.stop(); –

1

올바른 코드는 다음과 같습니다

// Create a new button and place it into a table row 
    LinearLayout lnr = (LinearLayout) findViewById(R.id.tableRow3); 
    Button b1 = new Button(this); 
    lnr.addView(b1); 

    // Associate the event 
    b1.setOnTouchListener(new OnTouchListener() { 
     MediaPlayer mp = new MediaPlayer(); 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      switch(event.getAction() & MotionEvent.ACTION_MASK) { 
      case MotionEvent.ACTION_DOWN: 
       // Finger started pressing --> play sound in loop mode 
       try { 
        FileInputStream fileInputStream = new FileInputStream(PATH); 
        mp.setDataSource(fileInputStream.getFD()); 
        mp.prepare(); 
        mp.setLooping(true); 
        mp.start(); 
       } catch (Exception e) {} 
      break; 
      case MotionEvent.ACTION_UP: 
       // Finger released --> stop playback 
       try { 
        mp.stop(); 
        mp.reset(); 
       } catch (Exception e) {} 
      break; 
      } 
      return true; 
     } 
     }); 
관련 문제