title: Android Studio: Start and Stop audio using mediaPlayer
body: <p>How to <code>start</code> and <code>stop</code> playing the music using the same button. The code below will play the song multiple times (overlaping) if I click it repeatedly.</p>
  
  <p>And another problem is where to insert <code>starTimer</code> and <code>StopTimer</code> function so the starTimer will active is the sound is not playing and stopTimer will active if the sound is playing.</p>
  
  <p>Updated Code:</p>
  
  <pre><code>   public void playFile(View v) {
      if (mediaPlayer == null)
          mediaPlayer = new MediaPlayer();
  
      try {
  
          mediaPlayer.setDataSource(question.getAudio());
  
          mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
              @Override
              public void onPrepared(@NotNull MediaPlayer mp) {
                  mediaPlayer.start();
              }
          });
          mediaPlayer.prepareAsync();
  
      }catch (IOException e) {
          e.printStackTrace();
          stopSelf();
      }
  
      if (mediaPlayer.isPlaying()) {
          //pause music
          mediaPlayer.pause();
      } else {
          //play music
          mediaPlayer.start();
      }
  }
  </code></pre>
  
  <p>Xml file:</p>
  
  <pre><code>&lt;Button
      android:id="@+id/audQuestion"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Play"
      android:onClick="playFile"
      android:layout_centerInParent="true"/&gt;
  </code></pre>
  
  <p>and for the startTimer stopTimer function</p>
  
  <pre><code>public void starTimer() {
      timer = new Timer(Constant.TIME_PER_QUESTION, Constant.COUNT_DOWN_TIMER);
      timer.start();
  }
  
  public void stopTimer() {
      if (timer != null)
          timer.cancel();
  }
  </code></pre>