代碼直接可以運行
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;public class SystemDefaultAudioPlayer {// 強制使用的通用音頻格式private static final AudioFormat FORCE_FORMAT = new AudioFormat(44100.0f, // 采樣率16, // 位深度2, // 聲道(立體聲)true, // 有符號false // 小端);public static void main(String[] args) {// 解決控制臺輸出亂碼try {System.setOut(new java.io.PrintStream(System.out, true, StandardCharsets.UTF_8.name()));} catch (UnsupportedEncodingException e) {System.err.println("設置編碼失敗: " + e.getMessage());}// 請先在系統中將默認音頻輸出設備設置為CABLE OutputSystem.out.println("注意:請確保已在系統中將默認音頻輸出設備設置為CABLE Output");// 指定要播放的音頻文件路徑String audioFilePath = "D:\\download\\語音合成模版.wav"; // 替換為你的音頻文件路徑// 使用系統默認設備播放音頻playAudioWithSystemDefault(audioFilePath);}/*** 使用系統默認音頻設備播放音頻文件*/private static void playAudioWithSystemDefault(String filePath) {File audioFile = new File(filePath);if (!audioFile.exists()) {System.out.println("音頻文件不存在: " + filePath);return;}try {// 獲取原始音頻輸入流和格式AudioInputStream originalAudioStream = AudioSystem.getAudioInputStream(audioFile);AudioFormat originalFormat = originalAudioStream.getFormat();System.out.println("原始音頻格式: " + formatToString(originalFormat));// 強制轉換為通用格式AudioInputStream convertedStream = AudioSystem.getAudioInputStream(FORCE_FORMAT, originalAudioStream);System.out.println("已強制轉換為通用格式: " + formatToString(FORCE_FORMAT));// 獲取系統默認的音頻輸出線路DataLine.Info lineInfo = new DataLine.Info(SourceDataLine.class, FORCE_FORMAT);SourceDataLine line = (SourceDataLine) AudioSystem.getLine(lineInfo);line.open(FORCE_FORMAT);line.start();System.out.println("開始播放音頻...");// 播放音頻數據byte[] buffer = new byte[4096];int bytesRead;while ((bytesRead = convertedStream.read(buffer)) != -1) {line.write(buffer, 0, bytesRead);}// 完成播放line.drain();line.stop();line.close();convertedStream.close();originalAudioStream.close();System.out.println("音頻播放完成");} catch (UnsupportedAudioFileException e) {System.out.println("不支持的音頻文件格式: " + e.getMessage());} catch (LineUnavailableException e) {System.out.println("音頻線路不可用: " + e.getMessage());System.out.println("請嘗試更換為其他音頻格式或檢查系統音頻設備設置");} catch (IOException e) {System.out.println("文件操作錯誤: " + e.getMessage());}}/*** 將音頻格式轉換為易讀字符串*/private static String formatToString(AudioFormat format) {return String.format("%s, %.0f Hz, %d位, %s, %s",format.getEncoding(),format.getSampleRate(),format.getSampleSizeInBits(),format.getChannels() == 1 ? "單聲道" : "立體聲",format.isBigEndian() ? "大端" : "小端");}
}