0
我只想播放指定序列開始和結束的歌曲的一部分。我是新的在Java中使用歌曲。我寫了下面的代碼,但有些錯誤是因爲播放了整首歌曲。我應該修改什麼?如何在Java中播放歌曲的一部分?
public class Song implements LineListener {
\t /**
* this flag indicates whether the playback completes or not.
*/
boolean playCompleted;
/**
* Play a given audio file.
* @param audioFilePath Path of the audio file.
*/
void playFrame(String songName) {
\t File audioFile = new File(songName);
\t try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.addLineListener(this);
audioClip.open(audioStream);
int nrFrames = audioClip.getFrameLength();
audioClip.setLoopPoints(nrFrames/3, nrFrames/3*2);
audioClip.start();
while (!playCompleted) {
// wait for the playback completes
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
audioClip.close();
} catch (UnsupportedAudioFileException ex) {
System.out.println("The specified audio file is not supported.");
ex.printStackTrace();
} catch (LineUnavailableException ex) {
System.out.println("Audio line for playing back is unavailable.");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Error playing the audio file.");
ex.printStackTrace();
}
}
@Override
public void update(LineEvent event) {
LineEvent.Type type = event.getType();
if (type == LineEvent.Type.START) {
System.out.println("Playback started.");
} else if (type == LineEvent.Type.STOP) {
playCompleted = true;
System.out.println("Playback completed.");
}
}
public static void main(String[] args) {
String fileName1 = "song1.wav";
\t \t String fileName2 = "song2.wav";
Song player = new Song();
player.playFrame(fileName1);
Song player2 = new Song();
player2.playFrame(fileName2);
}
}
根據的Javadoc,似乎'當你玩用'loop'方法的循環,而不是用'start'方法setLoopPoints'會工作。我無法回答你的問題,但... – dotvav
@Diana,由於您使用的是RIFF波形,請閱讀您的自我樣本並將它們泵入您的音頻後端。您確切知道您的DSP管道中發生了什麼。 – user877329