用java 写一个wav 转mp3的程序
时间: 2023-07-28 13:10:52 浏览: 267
要将 WAV 转换为 MP3,需要使用第三方库。以下是使用 LAME 库进行转换的 Java 代码示例:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import javazoom.jl.converter.Converter;
import javazoom.jl.decoder.JavaLayerException;
public class WavToMp3Converter {
public static void main(String[] args) throws IOException, JavaLayerException {
String inputFilePath = "path/to/input/wav/file.wav";
String outputFilePath = "path/to/output/mp3/file.mp3";
convertWavToMp3(inputFilePath, outputFilePath);
}
public static void convertWavToMp3(String inputFilePath, String outputFilePath)
throws IOException, JavaLayerException {
File inputFile = new File(inputFilePath);
File outputFile = new File(outputFilePath);
// Copy the input file to a temporary file
File tempFile = new File(
FilenameUtils.getFullPath(outputFile.getAbsolutePath()) + "temp_" + outputFile.getName());
FileUtils.copyFile(inputFile, tempFile);
// Open the input and output streams
InputStream inputStream = new FileInputStream(tempFile);
OutputStream outputStream = new FileOutputStream(outputFile);
// Convert the WAV file to MP3
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputStream);
AudioFormat sourceFormat = audioInputStream.getFormat();
AudioFormat targetFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, sourceFormat.getSampleRate(), 16,
sourceFormat.getChannels(), sourceFormat.getChannels() * 2, sourceFormat.getSampleRate(),
false);
AudioInputStream pcmAudioInputStream = AudioSystem.getAudioInputStream(targetFormat, audioInputStream);
Converter converter = new Converter();
converter.convert(pcmAudioInputStream, outputStream);
// Clean up
inputStream.close();
outputStream.close();
audioInputStream.close();
pcmAudioInputStream.close();
FileUtils.deleteQuietly(tempFile);
}
}
```
请注意,这个示例代码依赖于 LAME 库,可以从以下网址下载:http://www.java2s.com/Code/Jar/l/Downloadlame070jar.htm
此外,还需要导入 Apache Commons IO 库。可以从以下网址下载:https://commons.apache.org/proper/commons-io/download_io.cgi
阅读全文