在Android App中稍有延迟播放声音

时间:2015-01-22 17:41:30

标签: android eclipse

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

但是使用下面的代码,当应用播放歌曲时,按钮点击和App播放声音之间会有延迟大约半秒

我该如何解决?

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;
                    }
                });

1 个答案:

答案 0 :(得分:0)

SoundPool类用于声音资源的低延迟播放。它使用MediaPlayer但将流加载到内存中以实现更快速的回放