Java Reference
In-Depth Information
The Player's five states and the state transition methods are summarized
in Figure 9.1. As you can see, once a player reaches the PREFETCHED
state, it is using all possible memory and resources to allow the immediate
start of media playing. As its resource consumption is at maximum, we
must not keep too many prefetched players together in memory; the risk
is of slowing down the application or even running out of memory.
close()
close()
CLOSED
close()
close()
start()
realize()
prefetch()
STARTED
UNREALIZED
REALIZED
PREFETCHED
deallocate()
stop()
deallocate()
Figure 9.1 Lifecycle of a Player object
You must also not reload media from the disk or the network frequently.
Let us say you want to play an MP3 file each time your game reaches
a certain stage. For this you create a Player , call start() on it, play
the sound, and close it to save memory. The next time the game reaches
the same stage, you do this all over again. Essentially, what's being done
here is to reload data constantly, from the disk or the network, since
calling close() on a Player effectively renders it unusable, by freeing
all resources it is using. This situation seems to conflict with the previous
one: if one must not reload data frequently or keep many prefetched
players in memory, what is the optimal approach for reusing sounds in
an application?
There are many answers to this question. First, if you need to use
multiple players, you want to make sure that the data they are using is
small and efficient. Second, keep only players that you need immediately
in the PREFETCHED state; all the others must be moved to the REALIZED
state, where they are not consuming scarce resources. This can be
achieved with a call to Player.deallocate() , which moves the
player back one state. Last, but not least, if you are using a player only
once, as soon as you are done with it, call close() so all its scarce
resources, media buffers and memory can be disposed of.
As we have already mentioned, MMAPI players use a lot of memory,
by holding buffers where media data is stored. Therefore it's necessary
that you use them efficiently with regards to memory, by calling close()
explicitly on an unused player, to free its resources as soon as possible. We
Search WWH ::




Custom Search