我刚按完按钮
播放声音但是我的声音比“哔”短,短于1秒
如何按下按钮播放声音,直到按下按钮?
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/adLinear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/colorAccent">
</LinearLayout>
</LinearLayout>
</ScrollView>
答案 0 :(得分:0)
使用OnTouchListener
bt.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN: // Button Pressed
mp.reset();
mp.setDataSource(mediapath);
mp.prepare();
mp.start();
return true;
case MotionEvent.ACTION_UP:// Button released
mp.stop();
return true;
}
return false;
}
});
答案 1 :(得分:0)
您可以使用以下代码:
bt.setOnTouchListener(this);
@Override
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction() ) {
case MotionEvent.ACTION_DOWN:
System.out.println("touch");
mp.setLooping(true);
mp.start();
break;
case MotionEvent.ACTION_UP:
System.out.println("up");
mp.pause();
break;
}
return true;
}
我做了一些研究,发现Android Mediaplayer
在循环时播放无间隙声音有问题。
请参阅:Gapless Playback with android MediaPlayer
我也找到了几个解决方案:
您还可以使用以下类:查看它是否有效..
public class LoopMediaPlayer {
public static final String TAG = LoopMediaPlayer.class.getSimpleName();
private Context mContext = null;
private int mResId = 0;
private int mCounter = 1;
private MediaPlayer mCurrentPlayer = null;
private MediaPlayer mNextPlayer = null;
public static LoopMediaPlayer create(Context context, int resId) {
return new LoopMediaPlayer(context, resId);
}
private LoopMediaPlayer(Context context, int resId) {
mContext = context;
mResId = resId;
mCurrentPlayer = MediaPlayer.create(mContext, mResId);
mCurrentPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mCurrentPlayer.start();
}
});
createNextMediaPlayer();
}
private void createNextMediaPlayer() {
mNextPlayer = MediaPlayer.create(mContext, mResId);
mCurrentPlayer.setNextMediaPlayer(mNextPlayer);
mCurrentPlayer.setOnCompletionListener(onCompletionListener);
}
private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
mCurrentPlayer = mNextPlayer;
createNextMediaPlayer();
Log.d(TAG, String.format("Loop #%d", ++mCounter));
}
};
}
使用它只需调用
LoopMediaPlayer.create(context, R.raw.sound_file_name);
mp.setLooping(true);