问题
me and a friend are programming a MP3 Player as a schoolproject. We are nearly finished and now stuck at the point where we try to programm a function to change the volume of the player. We are using:
- AudioDevice
- AdvancedPlayer
I know someone else asked the same question allready but I did not quite get the solution and I didn't want to respond to such an old question so I thought I'm just gonna ask again.
Cheers Timothy
回答1:
The easiest way to do this is to use jlayer via mp3spi which basically means you use jlayer via JavaSound. You can then set gain on the line as you would in JavaSound.
Firstly, you will need to add the following to your classpath:
- jl1.0.1.jar
- mp3spi1.9.5.jar
- tritonus_share.jar
...all of which are in the distribution for mp3spi (linked above).
Secondly, you will need to decode the AudioInputStream prior to playback.
AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
AudioFormat baseFormat = audioStream.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
AudioInputStream audioStream2 = AudioSystem.getAudioInputStream(decodedFormat, audioStream);
Then you play the decoded stream:
Clip clip = AudioSystem.getClip();
clip.open(audioStream2);
and JavaSound API controls are available:
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(-30.0f);
NOTE: Don't forget to close your resources, I've just shown the key points for this issue - familiarity with JavaSound is expected, read here.
回答2:
JLGUI is a good example of a UI-based JLayer app adjusting volume. You can get the source code in the tar.gz file. http://www.javazoom.net/jlgui/sources.html
if (src == ui.getAcVolume())
{
Object[] args = { String.valueOf(ui.getAcVolume().getValue()) };
String volumeText = MessageFormat.format(ui.getResource("slider.volume.text"), args);
ui.getAcTitleLabel().setAcText(volumeText);
try
{
int gainValue = ui.getAcVolume().getValue();
int maxGain = ui.getAcVolume().getMaximum();
if (gainValue == 0) theSoundPlayer.setGain(0);
else theSoundPlayer.setGain(((double) gainValue / (double) maxGain));
config.setVolume(gainValue);
}
catch (BasicPlayerException ex)
{
log.debug("Cannot set gain", ex);
}
}
来源:https://stackoverflow.com/questions/3134167/adjusting-volume-using-jlayer