Stop playing music

83 Views Asked by At

I have app with music on start. Lenght of music is 23s, but it's playing without stopping. Music starts to play in loop while. How to stop looping when music lenght is over?

public void start() {
  try {
    InputStream is = getClass().getResourceAsStream("/a.mid");
    midiPlayer = Manager.createPlayer(is, "audio/midi");
  } catch (Exception e) {
  }
  z = true;
  Thread t = new Thread(this);
  t.start();
}

public void stop() {
  z = false;
}

public void run() {
  Graphics g = getGraphics();
  while (z) {
    draw(g);
    inputKey();
    try {
      Thread.sleep(200);
      midiPlayer.start();
    } catch (Exception e) {
    };
  }
}
1

There are 1 best solutions below

2
On BEST ANSWER

The Player object only plays the music once, unless you instruct it to replay. One way of telling it to reply is to call midiPlayer.setLoopCount(10); to have it play 10 times. Another way of looping is to implement the PlayerListener and add this code:

public void playerUpdate(Player player, String event, Object eventData) {
  if (event.equals(PlayerListener.END_OF_MEDIA)) {
    try {
      player.start();
    } catch (Exception e) {}
  }
}

A third way of looping, which is a very bad way of doing it, is the way you have unintentionally done it here: By repeatedly calling midiPlayer.start(); inside your loop. ;-)

public void start() {
  try {
    InputStream is = getClass().getResourceAsStream("/a.mid");
    midiPlayer = Manager.createPlayer(is, "audio/midi");
  } catch (Exception e) {
  }
  z = true;
  Thread t = new Thread(this);
  t.start();
}

public void stop() {
  z = false;
}

public void run() {
  Graphics g = getGraphics();
  midiPlayer.start();
  while (z) {
    draw(g);
    inputKey();
    try {
      Thread.sleep(200);
    } catch (Exception e) {
    };
  }
}

More useful info about playing music with JavaME here: http://www.indiegamemusic.com/help.php?id=1