1

In my j2me application i have to play a small sound file each times user click on an item. But the issues is when i play sound file multiple times like after 10-14 times it gives me out of memory exception. Although i release the player each time i play the file but still it gives out of memory exception : Here is the code snippet,

public void playSound(String soundFile) {
    try{
        if (player!=null) {   
            try {
                player.deallocate(); //deallocate the unnecessary memory.
            } catch (Exception ex) {
                player=null;  
                System.gc();
            }
        }

        player = Manager.createPlayer(getClass().getResourceAsStream(musicFolder + soundFile), "audio/mpeg");
        // player = Manager.createPlayer(is, "audio/mpeg");
        player.realize();

        // get volume control for player and set volume to max
        VolumeControl vc = (VolumeControl) player.getControl("VolumeControl");
        if (vc != null) {
            vc.setLevel(100);
        }

        player.prefetch();
        player.start();
        isException=false;
    } catch (Exception e) {

         isException=true;
    }
}

Can someone tell me what is going wrong?

gnat
  • 6,213
  • 108
  • 53
  • 73
user1001084
  • 115
  • 1
  • 10
  • please add the handset manufacturer and model. also, an indication in the code that you know for sure what line of code throws what java.lang.Throwable – michael aubert Jul 17 '12 at 13:04

3 Answers3

3

3 things to keep in mind

  • If you are going to play the same sound several times, you might want to keep one Player prefetched and simply start it multiple times.

  • When you want to properly cleanup a player, you should call Player.close()

  • You may want to use a media event listener to close and/or restart a player independently of user input.

michael aubert
  • 6,836
  • 1
  • 16
  • 32
2

I think you should also call

player.close() 

right after after

player.deallocate();

According to documentation "When deallocate returns, the Player is in the UNREALIZED or REALIZED state." but close goes further... "When the method returns, the Player is in the CLOSED state and can no longer be used."

Telmo Pimentel Mota
  • 4,033
  • 16
  • 22
0

I'm not sure why the de-allocation isn't working. I guess it either takes longer to de-allocated than to create a new one, or the de-allocation fails for some reason. Is there a player.stop() to match the player.start()?

Another thing to try (if nothing else, for good form :) is not to create new player unless you need to/should. I.e. move the

  if(player!=null){   

So it also covers

    player = Manager.createPlayer(getClass().getResourceAsStream(musicFolder + soundFile), "audio/mpeg");

HTH!

Nava
  • 71
  • 1
  • 4