title: How to make a MediaPlayer stop after the object that contained it was set to null in Java?
body: <p>I created a <code>Sound</code> class for my game that contains a MediaPlayer which loops (in the scenario in which the problem occurs). If an object that contains a Sound object is set to null (to remove it) the MediaPlayer continues playing until it reaches the end of the media, altough it should stop since it should have been set to null. Or is that not how it works?</p>
  
  <p>I found the following posts online, but none of them had the same problem as I: <a href="https://stackoverflow.com/questions/6946492/how-do-i-make-a-mediaplayer-stop-when-another-mediaplayer-starts-so-that-they-do">Link1</a>, <a href="https://stackoverflow.com/questions/20754272/how-do-i-release-my-media-player-after-it-is-done-playing">Link2</a></p>
  
  <p>This is the <code>Sound</code> class:</p>
  
  <pre><code>public classs Sound {
  
    MediaPlayer mediaPlayer;
  
    public Sound(String path){
      Media media = new Media(getClass().getResource("/audio/" + path).toString());
      mediaPlayer = new MediaPlayer(media);
    }
  
    public void loop(){
      //only called once after initialized
      mediaPlayer.setAutoPlay(true);
      mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
      mediaPlayer.setOnEndOfMedia(new Runnable() {
          @Override
          public void run() {
              mediaPlayer.seek(Duration.ZERO);
              mediaPlayer.play();
          }
      });
      mediaPlayer.play();
    }
  }
  </code></pre>
  
  <p>This is the sound containing class:</p>
  
  <pre><code>public class Level {
  
      private Sound soundTrack = new Sound("level_music.wav");
  
      public Level() {
          soundTrack.loop();
      }
  </code></pre>
  
  <p>This is how the sound-containing object is set to null:</p>
  
  <pre><code>public class Main{
  
    private Level level = new Level();
    //...
    public Main(){
      new Timer(15, new ActionListener() {
  
        @Override
        public void actionPerformed(ActionEvent e) {
  
          if(playerLeavesTheLevel()){
            level = null;
            //...
          }
  
      }
    }
  }
  </code></pre>
  
  <p>The only reason this doesn't work is because the mediaPlayer is not set to null once the top-level object is removed.</p>