将Android Mediaplayer更改为Soundpool

时间:2019-02-11 11:24:52

标签: android-mediaplayer soundpool

Mediaplayer功能面临的问题。 多按按钮时声音没有停止。 如果快速轻按按钮,声音会停止。

package com.shockverse.pkhorns;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;



public class CallFragment extends Fragment implements View.OnTouchListener {

private MediaPlayer mp;
private int[] sounds = {R.raw.a1,R.raw.a2,R.raw.a3,R.raw.a4,R.raw.a5,R.raw.a6};
private int[] btns = {R.id.button,R.id.button2,R.id.button3,R.id.button4,R.id.button5,R.id.button6};


public CallFragment() {
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_call, container, false);
    for (int btn : btns) {
        ((Button) view.findViewById(btn)).setOnTouchListener(this);
    }
    return view;
}


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

        case MotionEvent.ACTION_DOWN: {
            for (int i = 0 ; i<btns.length ; i++){
                if (v.getId() == btns[i]){
                    mp = MediaPlayer.create(getActivity(), sounds[i]);
                    v.setBackgroundResource(R.drawable.b);
                    break;
                }
            }
            mp.setLooping(true);
            mp.start();
        }

        break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL: {

            for (int btn : btns) {
                if (v.getId() == btn) {
                    v.setBackgroundResource(R.drawable.a);
                    mp.pause();
                    break;
                }
            }
        }
        break;
    }
    return true;    }

}

与媒体播放器相比,声音播放可以流畅地播放简​​短的OntouchListener声音。因此,我需要将我的代码更改为声音池功能。

0 个答案:

没有答案