Media Player start stop start

后端 未结 9 1990
死守一世寂寞
死守一世寂寞 2020-12-10 13:09

I am making a new android sound application. I made a clickable button to play sound when I click on it. But I also want it to stop playing sound when I click for the second

9条回答
  •  醉梦人生
    2020-12-10 13:18

    I know that this question is quite old but recently while learning Android, I also got stuck at this point and found a very simple solution which I'd like to share with everyone.

    Instead of trying to stop or reset the media, you can just seek back to the starting position.

    mediaPlayer.seekTo(0);
    

    For reference, I am also posting my code below:

    public class MainActivity extends AppCompatActivity {
    
        MediaPlayer mp;
    
        public void play(View view) {
            mp.start();
        }
    
        public void pause(View view) {
            mp.pause();
        }
    
        public void stop(View view) {
            // this seeks to the beginning of the file
            mp.seekTo(0);
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mp = MediaPlayer.create(this, R.raw.sample_audio);
        }
    }
    

提交回复
热议问题