Added method to get duration of MP3s.

Currently used for the music bar in the main menu.

Signed-off-by: Jeffrey Han <itdelatrisu@gmail.com>
This commit is contained in:
Jeffrey Han 2015-03-16 13:16:30 -04:00
parent 678f902744
commit f23159d003
2 changed files with 33 additions and 3 deletions

View File

@ -24,8 +24,14 @@ import itdelatrisu.opsu.OsuFile;
import itdelatrisu.opsu.OsuParser;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.IntBuffer;
import java.util.Map;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.lwjgl.BufferUtils;
import org.lwjgl.openal.AL;
@ -35,6 +41,7 @@ import org.newdawn.slick.MusicListener;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.openal.Audio;
import org.newdawn.slick.openal.SoundStore;
import org.tritonus.share.sampled.file.TAudioFileFormat;
/**
* Controller for all music.
@ -252,6 +259,30 @@ public class MusicController {
return (trackExists() && position >= 0 && player.setPosition(position / 1000f));
}
/**
* Returns the duration of the current track, in milliseconds.
* Currently only works for MP3s.
* @return the duration, or -1 if no track exists, else the {@code endTime}
* field of the OsuFile loaded
* @author Tom Brito (http://stackoverflow.com/a/3056161)
*/
public static int getDuration() {
if (!trackExists() || lastOsu == null)
return -1;
if (lastOsu.audioFilename.getName().endsWith(".mp3")) {
try {
AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(lastOsu.audioFilename);
if (fileFormat instanceof TAudioFileFormat) {
Map<?, ?> properties = ((TAudioFileFormat) fileFormat).properties();
Long microseconds = (Long) properties.get("duration");
return (int) (microseconds / 1000);
}
} catch (UnsupportedAudioFileException | IOException e) {}
}
return lastOsu.endTime;
}
/**
* Plays the current track.
* @param loop whether or not to loop the track

View File

@ -239,7 +239,7 @@ public class MainMenu extends BasicGameState {
g.fillRoundRect(musicBarX, musicBarY, musicBarWidth, musicBarHeight, 4);
g.setColor(Color.white);
if (!MusicController.isTrackLoading() && osu != null) {
float musicBarPosition = Math.min((float) MusicController.getPosition() / osu.endTime, 1f);
float musicBarPosition = Math.min((float) MusicController.getPosition() / MusicController.getDuration(), 1f);
g.fillRoundRect(musicBarX, musicBarY, musicBarWidth * musicBarPosition, musicBarHeight, 4);
}
@ -430,8 +430,7 @@ public class MainMenu extends BasicGameState {
if (MusicController.isPlaying()) {
if (musicPositionBarContains(x, y)) {
float pos = (x - musicBarX) / musicBarWidth;
OsuFile osu = MusicController.getOsuFile();
MusicController.setPosition((int) (pos * osu.endTime));
MusicController.setPosition((int) (pos * MusicController.getDuration()));
return;
}
}