Search code examples
androidaudiomedia-player

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


Solution

  • 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.