如何在Java中播放API返回的Base64编码音频字符串?
解决Java播放TTS API返回音频时的“Stream of unsupported format”错误
问题核心是Java原生AudioSystem不支持该API返回的音频格式(这类TTS API常用MP3作为输出格式,而Java原生无MP3支持),以下是具体解决步骤:
1. 先确认音频格式
把Base64解码后的字节保存为本地文件,验证具体格式:
private static void saveAudioFile(String audioString, String filePath) throws IOException { byte[] decoded = Base64.getDecoder().decode(audioString); try (FileOutputStream fos = new FileOutputStream(filePath)) { fos.write(decoded); } }
调用方法保存后,用本地播放器查看文件属性,确认是MP3、OGG还是其他格式。
2. 引入对应格式的支持库
如果是MP3格式
使用轻量级的JLayer库,Maven依赖如下:
<dependency> <groupId>javazoom</groupId> <artifactId>jlayer</artifactId> <version>1.0.1</version> </dependency>
如果是OGG格式
引入VorbisSPI库,让AudioSystem能识别OGG格式:
<dependency> <groupId>com.googlecode.soundlibs</groupId> <artifactId>vorbisspi</artifactId> <version>1.0.3.3</version> </dependency>
3. 修改播放代码
MP3格式的播放代码
直接用JLayer提供的Player类:
import javazoom.jl.player.Player; import java.io.ByteArrayInputStream; import java.util.Base64; private static void playAudio(String audioString) { try { // 若API返回的字符串带前缀(如data:audio/mp3;base64,),需先截取 if (audioString.startsWith("data:audio/")) { audioString = audioString.split(",")[1]; } byte[] decoded = Base64.getDecoder().decode(audioString); Player player = new Player(new ByteArrayInputStream(decoded)); player.play(); } catch (Exception e) { e.printStackTrace(); } }
OGG格式的播放代码
引入VorbisSPI后,可复用你原有的AudioSystem逻辑:
import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import java.io.ByteArrayInputStream; import java.util.Base64; private static void playAudio(String audioString) { try { if (audioString.startsWith("data:audio/")) { audioString = audioString.split(",")[1]; } byte[] decoded = Base64.getDecoder().decode(audioString); AudioInputStream audioIn = AudioSystem.getAudioInputStream(new ByteArrayInputStream(decoded)); Clip song = AudioSystem.getClip(); song.open(audioIn); song.start(); // 等待播放完成 Thread.sleep(song.getMicrosecondLength() / 1000); } catch (Exception e) { e.printStackTrace(); } }
额外提示
- 优先查看API文档,确认是否支持指定输出为PCM编码的WAV格式(Java原生支持),若支持可直接在调用API时指定格式,无需引入第三方库。
- 解码前务必检查Base64字符串是否带有
data:audio/xxx;base64,前缀,需去掉后再解码。
内容的提问来源于stack exchange,提问作者Becker
相关产品推荐
相关产品推荐

