如何使用Java将OGG文件转换为WAV文件?
Telegram机器人OGG转WAV的Java实现方案
针对Telegram语音消息(OGG格式)转WAV以适配微软语音转文本Java SDK的需求,以下是三种可行的实现方案:
方案一:FFmpeg命令行调用(稳定高效)
借助FFmpeg处理音频格式转换,需确保运行环境已安装FFmpeg。转换时指定微软SDK要求的PCM参数:
import java.io.IOException; public class OggToWavConverter { public static void convertOggToWav(String oggFilePath, String wavFilePath) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder( "ffmpeg", "-i", oggFilePath, "-acodec", "pcm_s16le", "-ar", "16000", "-ac", "1", wavFilePath ); Process process = processBuilder.start(); try { int exitCode = process.waitFor(); if (exitCode != 0) { throw new RuntimeException("FFmpeg转换失败,退出码: " + exitCode); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("转换被中断", e); } } }
方案二:纯Java库TarsosDSP(无外部依赖)
使用TarsosDSP纯Java音频处理库,无需安装外部工具,适合轻量场景:
先添加Maven依赖
<dependency> <groupId>be.tarsos.dsp</groupId> <artifactId>tarsos-dsp</artifactId> <version>2.4.0</version> </dependency>
转换代码
import be.tarsos.dsp.AudioDispatcher; import be.tarsos.dsp.io.jvm.AudioDispatcherFactory; import be.tarsos.dsp.io.jvm.WaveWriter; import java.io.File; import java.io.IOException; public class OggToWavConverter { public static void convertWithTarsos(String oggPath, String wavPath) throws IOException { AudioDispatcher dispatcher = AudioDispatcherFactory.fromPipe(oggPath, 16000, 1024, 0); WaveWriter waveWriter = new WaveWriter(new File(wavPath), 16000, 1); dispatcher.addAudioProcessor(waveWriter); dispatcher.run(); } }
方案三:JAVE2封装库(跨平台友好)
JAVE2封装了FFmpeg功能,自动适配不同系统的native库,无需手动安装FFmpeg:
添加Maven依赖
<dependency> <groupId>ws.schild</groupId> <artifactId>jave-core</artifactId> <version>3.1.1</version> </dependency> <!-- 根据运行系统选择对应native依赖,示例为Windows x64 --> <dependency> <groupId>ws.schild</groupId> <artifactId>jave-nativebin-win64</artifactId> <version>3.1.1</version> </dependency>
转换代码
import ws.schild.jave.Encoder; import ws.schild.jave.EncoderException; import ws.schild.jave.MultimediaObject; import ws.schild.jave.encode.AudioAttributes; import ws.schild.jave.encode.EncodingAttributes; import java.io.File; public class OggToWavConverter { public static void convertWithJave(String oggPath, String wavPath) throws EncoderException { File source = new File(oggPath); File target = new File(wavPath); AudioAttributes audio = new AudioAttributes(); audio.setCodec("pcm_s16le"); audio.setBitRate(16000); audio.setChannels(1); audio.setSamplingRate(16000); EncodingAttributes attrs = new EncodingAttributes(); attrs.setFormat("wav"); attrs.setAudioAttributes(audio); Encoder encoder = new Encoder(); encoder.encode(new MultimediaObject(source), target, attrs); } }
关键注意事项
- 微软语音转文本SDK要求WAV格式为PCM 16位、单声道、16kHz采样率,所有方案均已按此配置参数,请勿随意修改。
- 处理Telegram语音时,需先将文件从Telegram服务器下载至本地,再执行转换,转换完成后再传入微软SDK进行转写。
内容的提问来源于stack exchange,提问作者djy
相关产品推荐
相关产品推荐

