Search code examples
javaandroidandroid-studiomedia-player

play and pause music using android application


I m trying to build an app that read a music file and I use a button to play/pause the music so I used the code bellow and the problem that I have is that once I click on the button the music is played and then when i click it is stopped so when I click for the third time the music is not played (it is played only once)

 btn1=(Button)findViewById(R.id.btn) ;
 try {
            mp.setDataSource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +String.valueOf("/myfile.3gp"));
        } catch (IOException e) {
            e.printStackTrace();
        }

 btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{

                  if(!mp.isPlaying()){
                      mp.prepare();
                      mp.start();
                      btn1.setText("pause");

                  }else{
                      mp.pause();
                      btn1.setText("play");

                    }

                }catch(Exception e){e.printStackTrace();}
            }
        });

Solution

  • I think you only need to call mp.prepare(); once, since it should already be created after the first time you press "Play". You could use an onPrepared method. Maybe this link might help: this