首先引入依赖:
<!-- https://mvnrepository.com/artifact/net.sf.jacob-project/jacob -->
<dependency>
<groupId>net.sf.jacob-project</groupId>
<artifactId>jacob</artifactId>
<version>1.14.3</version>
</dependency>
可以使用Jacob库结合Java Sound API来播放语音文件流。
import com.jacob.com.LibraryLoader;
import com.jacob.com.Dispatch;
import com.jacob.activeX.ActiveXComponent;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class JacobAudioPlayer {
static {
// 加载Jacob库
String jacobPath = "path_to_jacob.dll"; // 请替换为实际的Jacob库文件路径
System.setProperty(LibraryLoader.JACOB_DLL_PATH, jacobPath);
}
public static void main(String[] args) {
String audioFilePath = "path_to_audio_file.wav"; // 请替换为实际的音频文件路径
// 使用Java Sound API播放音频文件流
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(audioFilePath));
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioInputStream.getFormat());
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
line.open(audioInputStream.getFormat());
line.start();
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = audioInputStream.read(buffer)) != -1) {
line.write(buffer, 0, bytesRead);
}
line.drain();
line.close();
audioInputStream.close();
} catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) {
e.printStackTrace();
}
// 使用Jacob播放音频文件流 msdxm.OCX调用系统扬声器
ActiveXComponent mediaPlayer = new ActiveXComponent("msdxm.OCX");
Dispatch.put(mediaPlayer, "URL", audioFilePath);
Dispatch.call(mediaPlayer, "controls", "play");
// 等待音频播放完成
try {
Thread.sleep(10000); // 在这里等待10秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
// 关闭Jacob播放器
Dispatch.call(mediaPlayer, "close");
}
}