2011-03-09 246 views
5

我有这样的代码在按下按钮播放声音-Android

package com.tct.soundTouch; 

import android.app.Activity; 
import android.media.MediaPlayer; 
import android.os.Bundle; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnTouchListener; 
import android.widget.Button; 

public class main extends Activity implements OnTouchListener { 

    private MediaPlayer mp; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     final Button zero = (Button) this.findViewById(R.id.button); 
     zero.setOnTouchListener(this); 

     mp = MediaPlayer.create(this, R.raw.sound); 

    } 

    @Override 
    public boolean onTouch(View v, MotionEvent event) { 

     switch (event.getAction()) { 

     case MotionEvent.ACTION_DOWN: 
      mp.setLooping(true); 
      mp.start(); 

     case MotionEvent.ACTION_UP: 
      mp.pause(); 
     } 

     return true; 
    } 

} 

和它的作品,但并不如我所料。声音播放,但每次我按下按钮。我的想法是。当我按下按钮声音播放时,当我停止动作(手指离开按钮)音乐暂停。

有什么想法吗?

感谢

+2

它只是增加回报忠实于每一种情况下,现在的作品 – anvd 2011-03-09 23:14:05

+0

烨,或break语句。要么会工作。 – kcoppock 2011-03-09 23:20:17

+0

@Fel您应该将其作为回答发布,如果能解决您的问题,请接受它。 – 2011-11-10 16:35:06

回答

3

这应该工作(有我觉得有什么不对您的开关的情况下):

@Override 
public boolean onTouch(View v, MotionEvent event) 
{ 

    switch (event.getAction()) 
    { 

    case MotionEvent.ACTION_DOWN: 
    { 
     mediaPlayer.setLooping(true); 
     mediaPlayer.start(); 
    } 

    break; 
    case MotionEvent.ACTION_UP: 
    { 
     mediaPlayer.pause(); 
    } 
    break; 
} 

return true; 
}