因此,我试图让 Java 在这方面以一定的速度播放声音,我尝试为 SourceDataLine 获得一个用于采样率的控件:
`package com.pap.sound;
import javax.sound.sampled.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.BitSet;
public class Player implements Playable {
private AudioFormat format;
private SourceDataLine sourceDataLine;
private DataLine.Info info;
private final URL soundUrl;
private final boolean[] stopped;
private float playRate;
private boolean playRateChanged;
public Player(URL soundUrl) throws LineUnavailableException, MalformedURLException {
this.format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,44100, 16, 2 , 4, 44100,false);
this.info = new DataLine.Info(SourceDataLine.class, format);
this.sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
this.soundUrl = soundUrl;
this.stopped = new boolean[1];
this.stopped[0] = false;
this.playRate = 1;
this.playRateChanged = false;
}
@Override
public boolean play() throws LineUnavailableException {
sourceDataLine.open();
Thread playerThread = new Thread(){
@Override
public void run() {
int numberOfBitesRead = 0;
AudioInputStream auis = null;
try {
auis = AudioSystem.getAudioInputStream(soundUrl);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = new byte[4];
sourceDataLine.start();
try {
auis.mark(auis.available());
while(!stopped[0]) {
numberOfBitesRead = auis.read(bytes);
if(numberOfBitesRead == -1) {
auis.reset();
}
sourceDataLine.write(bytes, 0, bytes.length);
FloatControl fc = (FloatControl) sourceDataLine.getControl(FloatControl.Type.SAMPLE_RATE);
if(playRateChanged) {
fc.setValue((int)(44200*playRate));
playRateChanged = false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
playerThread.start();
return false;
}
@Override
public boolean stop() {
this.stopped[0] = true;
this.sourceDataLine.stop();
this.sourceDataLine.close();
return false;
}
@Override
public boolean setPlayRate(float playRate) {
this.playRate = playRate;
this.playRateChanged = true;
return false;
}
}`
但在运行时我得到:
Exception in thread "Thread-1" java.lang.IllegalArgumentException: Unsupported control type: Sample Rate
at com.sun.media.sound.AbstractLine.getControl(AbstractLine.java:150)
at com.pap.sound.Player$1.run(Player.java:67)