开发者

Android, lag in music playing when button pressed

I have two buttons in a very simple app, this is my code when either of those buttons are clicked:

 public void button_clicked1(View v) 
    {
        text1.setText("1"+width);  

         mp = MediaPlayer.create(GameScreen.this, R.raw.piano_a);   
             try {
                    mp .prepare();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
            开发者_如何学JAVA    }
         mp.start();



        }


    public void button_clicked2(View v) 
    {
        text1.setText("2"+height);    
        mp = MediaPlayer.create(GameScreen.this, R.raw.piano_b);   
        /*
            try {
                mp .prepare();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }*/
     mp.start();
        }

Each of those raw piano notes is around 20 secs... but when i press either one of the button i want it to play the file immediately... but I find there is a lag (and the lag keeps getting bigger) and sometimes if i press both the buttons quick a few times... it force quits :(


According to the docs, when loading a raw audio file (properly encoded), you don't need to call prepare, just:

MediaPlayer mediaPlayer = MediaPlayer.create(GameScreen.this, R.raw.piano_a);
mediaPlayer.start();

This should do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜