在安卓应用程序中小延迟后播放声音



我的应用程序中有很多按钮,还有很多短歌可以像钢琴等一样弹奏。

但是使用以下代码,当应用程序播放歌曲时,在按钮单击和应用程序播放声音之间有大约半秒的延迟

我该如何解决它?

public class MainActivity extends Activity {
    MediaPlayer mp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        final Button g1 = (Button) findViewById(R.id.bu1);
        final Button g2 = (Button) findViewById(R.id.bu2);
        final Button g3 = (Button) findViewById(R.id.bu3);
        final Button g4 = (Button) findViewById(R.id.bu4);
        final Button g5 = (Button) findViewById(R.id.bu5);



                g1.setOnTouchListener(new OnTouchListener() {
                    MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.closehh);
                    @Override
                     public boolean onTouch(View view, MotionEvent motionevent) 
                    { 
                        int action = motionevent.getAction(); 
                        if (action == MotionEvent.ACTION_DOWN) 
                        {         
                                   mp.start();
                                   mp.seekTo(0);
                                   g1.setBackgroundResource(R.drawable.a0005z);
                        }
                        if (action == MotionEvent.ACTION_UP){
                            g1.setBackgroundResource(R.drawable.a0005);
                        }
                        return false;
                    }
                });
                g2.setOnTouchListener(new OnTouchListener() {
                    MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.openhh);
                    @Override
                     public boolean onTouch(View view, MotionEvent motionevent) 
                    { 
                        int action = motionevent.getAction(); 
                        if (action == MotionEvent.ACTION_DOWN) 
                        {         
                                   mp.start();
                                   mp.seekTo(0);
                                   g2.setBackgroundResource(R.drawable.a0005z);
                        }
                        if (action == MotionEvent.ACTION_UP){
                            g2.setBackgroundResource(R.drawable.a0005);
                        }
                        return false;
                    }
                });

SoundPool 类用于声音资源的低延迟播放。它使用媒体播放器,但将流加载到内存中以实现更灵敏的播放

最新更新