J2me Player, Play MP3 Files One After The Other
I am unable to play an MP3 file one after the other, when 1 file finishes playing the other file needs to start. I am only able to s开发者_如何学JAVAtart playing 1 file, when I put code to start the next file it just does nothing. For some reasons I cannot use thread.sleep()
for the duration of file. Is there any other way to do this?
//this is the basic code..
playq(String fname){
pl = Manager.createPlayer(stream,"audio/mpeg");
pl.realize();
pl.prefetch();
pl.start();
// what should i use here?? pls i don't want to use thread.sleep..
playagain(fname);
}
void playagain(String fname){
try {
pl.stop();
pl.deallocate();
pl.close();
} catch (Exception ex) {}
//change file name and stream and..
playq(mp3f);
}
Your code should NOT attempt to play the code from a catch
block - for one thing, it's only going to be called if an exception was generated (You also generally shouldn't be blanket-catching Exception
- use something more specific).
Are you sure you can't use Thread.sleep()
? Granted you're not really going to want to anyways (for instance, if the user can pause the clip...).
Instead, look into using the PlayerListener
interface, and listen for END_OF_MEDIA
events.
A really basic (as in, this isn't tested, and needs more work besides) example:
public class PlayerRunner implements PlayerListener {
private final String[] songFiles;
private int songIndex = 0;
public PlayerRunner(String[] songs) {
this.songFiles = songs;
}
public void start() {
playerUpdate(null, null, null);
}
// This method is required by the PlayerListener interface
public void playerUpdate(Player player, String event, Object eventData) {
// The first time through all parameters will be blank/null...
boolean nextSong = (event == null);
if (event == PlayerListener.END_OF_MEDIA) {
player.stop();
player.dallocate();
player.close();
nextSong = index < songIndex.length;
}
if (nextSong) {
String fileName = songFiles[index++];
if (fileName != null) {
Player pl = Manager.createPlayer(fileName, "audio/mpeg");
pl.addPlayerListener(this);
pl.realize();
pl.prefetch();
pl.start();
}
}
}
}
Please note that I'm not doing this completely correctly - I'm not doing exception handling, for example. Also, without knowing more about your situation, I don't know what other things to worry about. This should just be a simple answer to get you started looking at where you should be going with this.
(Also, I've never worked with the media player of JME, so I don't know any caveats about the GC there, etc).
精彩评论