杰瑞科技汇

Java如何将MP3转为WAV格式?

Of course! Converting an MP3 file to WAV in Java is a common task, but it requires an external library because the standard Java Development Kit (JDK) doesn't include MP3 decoding capabilities.

Java如何将MP3转为WAV格式?-图1
(图片来源网络,侵删)

The most popular and reliable library for this is JAVE (Java Audio Video Encoder). It's a Java wrapper around the powerful FFmpeg command-line tool.

Here’s a complete guide, from setup to a working code example.

Why Do We Need a Library?

  • MP3 is a compressed format. It uses lossy compression to reduce file size.
  • WAV is an uncompressed format. It's essentially a raw audio data file.
  • Java's javax.sound.sampled can read and write WAV files, but it cannot decode the MP3 format. It needs the audio data already decoded into a format it understands (like PCM).

JAVE handles this complexity for you by using FFmpeg's engine behind the scenes.


Step 1: Add the JAVE Library to Your Project

You need to add the JAVE library (a JAR file) to your project's classpath. The easiest way to do this with modern build tools is using Maven or Gradle.

Java如何将MP3转为WAV格式?-图2
(图片来源网络,侵删)

Using Maven (Recommended)

Add the following dependency to your pom.xml file:

<dependencies>
    <dependency>
        <groupId>ws.schild</groupId>
        <artifactId>jave-core</artifactId>
        <version>3.3.1</version> <!-- Check for the latest version -->
    </dependency>
    <!-- You might also need this for native support on some systems -->
    <dependency>
        <groupId>ws.schild</groupId>
        <artifactId>jave-nativebin-win64</artifactId>
        <version>3.3.1</version> <!-- Must match the core version -->
        <scope>runtime</scope>
    </dependency>
</dependencies>

Note: If you're on Linux or macOS, you would use jave-nativebin-linux64 or jave-nativebin-macosx respectively.

Using Gradle

Add the following dependency to your build.gradle file:

dependencies {
    implementation 'ws.schild:jave-core:3.3.1' // Check for the latest version
    runtimeOnly 'ws.schild:jave-nativebin-win64:3.3.1' // For Windows
    // Use 'ws.schild:jave-nativebin-linux64' for Linux
    // Use 'ws.schild:jave-nativebin-macosx' for macOS
}

Manual Download (If you don't use a build tool)

  1. Go to the JAVE Maven Repository.
  2. Download the latest jave-core-<version>.jar.
  3. Download the corresponding native binary JAR for your operating system (e.g., jave-nativebin-win64-<version>.jar).
  4. Add both JAR files to your project's libraries/dependencies.

Step 2: Create a Java Class for the Conversion

Now, let's write the Java code. This example will show you how to convert a single MP3 file to a WAV file.

Java如何将MP3转为WAV格式?-图3
(图片来源网络,侵删)

The core logic is:

  1. Create an Encoder object.
  2. Define the source (MP3) and target (WAV) files.
  3. Specify the encoding parameters for the output format.
  4. Call the encode method.

Here is a complete, runnable example:

import ws.schild.jave.*;
import java.io.File;
public class Mp3ToWavConverter {
    public static void main(String[] args) {
        // Define the input MP3 file and the output WAV file
        File source = new File("input.mp3");
        File target = new File("output.wav");
        // --- IMPORTANT ---
        // Make sure you have an "input.mp3" file in the same directory as your program,
        // or provide the full path to the file.
        if (!source.exists()) {
            System.err.println("Error: Source file 'input.mp3' not found!");
            System.err.println("Please place an MP3 file named 'input.mp3' in the project root.");
            return;
        }
        try {
            System.out.println("Starting conversion...");
            // 1. Create an Encoder instance
            Encoder encoder = new Encoder();
            // 2. Specify the audio format for the output WAV file
            //    We are creating an uncompressed WAV file (PCM audio)
            AudioAttributes audio = new AudioAttributes();
            audio.setCodec("pcm_s16le"); // PCM signed 16-bit little-endian
            audio.setChannels(2);         // Stereo
            audio.setSamplingRate(44100); // CD quality sample rate
            // 3. Set up the encoding parameters
            //    We are not creating a video file, so video attributes can be null.
            //    The format specifies the container format (WAV in this case).
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setFormat("wav");
            attrs.setAudioAttributes(audio);
            // 4. Perform the encoding
            encoder.encode(source, target, attrs);
            System.out.println("Conversion completed successfully!");
            System.out.println("Output file saved to: " + target.getAbsolutePath());
        } catch (EncoderException e) {
            System.err.println("An error occurred during encoding:");
            e.printStackTrace();
        }
    }
}

How to Run the Code

  1. Save the code: Save the code above as Mp3ToWavConverter.java.

  2. Get an MP3 file: Place an MP3 file named input.mp3 in the same directory where you will run your Java code. You can name it whatever you want, just make sure to update the File source = new File("..."); line accordingly.

  3. Compile and Run:

    • If using an IDE (like IntelliJ or Eclipse): Add the JAVE JARs to your project's libraries and run the main method.

    • If using the command line:

      # Compile the Java file (make sure jave-core.jar is in the same directory or in your classpath)
      # The -cp flag sets the classpath.
      javac -cp ".:jave-core-3.3.1.jar" Mp3ToWavConverter.java 
      # Run the compiled class
      java -cp ".:jave-core-3.3.1.jar" Mp3ToWavConverter 

      Note: On Windows, the classpath separator is a semicolon (), not a colon ().

After running, you will see a new file named output.wav in your directory. It will be significantly larger than the original MP3 file because it's uncompressed.


Key Options and Customization

You can easily customize the output by changing the AudioAttributes.

To change the sample rate (e.g., 22,050 Hz):

audio.setSamplingRate(22050);

To create a mono audio file (1 channel):

audio.setChannels(1);

To change the bit depth (e.g., 8-bit):

audio.setCodec("pcm_u8"); // PCM unsigned 8-bit

Alternative: Using pure Java (without FFmpeg)

If you absolutely cannot use a native library, there are pure Java MP3 decoders, but they are generally slower and less robust. The most common one is JLayer.

Disadvantages of this approach:

  • Slower: Pure Java decoding is CPU-intensive.
  • More Code: You have to manually read the MP3, decode it to raw PCM data, and then write that data into a WAV file structure.
  • Complexity: You have to handle the WAV file header format yourself.

Example using JLayer:

  1. Add JLayer dependency (Maven):

    <dependency>
        <groupId>com.googlecode.soundlibs</groupId>
        <artifactId>mp3spi</artifactId>
        <version>1.9.5.4</version>
    </dependency>

    (Note: mp3spi is a popular bundle that includes JLayer and integrates it with JavaSound).

  2. Java Code:

    import javax.sound.sampled.*;
    java.io.File;
    java.io.IOException;
    public class Mp3ToWavConverterJLayer {
        public static void main(String[] args) throws UnsupportedAudioFileException, IOException {
            File sourceFile = new File("input.mp3");
            File targetFile = new File("output_jlayer.wav");
            // Get the input stream from the MP3 file
            AudioInputStream mp3Stream = AudioSystem.getAudioInputStream(sourceFile);
            // Get the format of the input stream
            AudioFormat sourceFormat = mp3Stream.getFormat();
            // Define the desired WAV format (uncompressed PCM)
            AudioFormat targetFormat = new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED,
                sourceFormat.getSampleRate(), // Keep the original sample rate
                16,                           // 16-bit
                sourceFormat.getChannels(),   // Keep the original channels
                sourceFormat.getSampleRate() * sourceFormat.getChannels() * 2, // Frame size
                sourceFormat.getSampleRate(), // Frame rate
                false                         // Little-endian
            );
            // Convert the input stream to the target format
            AudioInputStream convertedStream = AudioSystem.getAudioInputStream(targetFormat, mp3Stream);
            // Write the converted stream to a WAV file
            AudioSystem.write(convertedStream, AudioFileFormat.Type.WAVE, targetFile);
            System.out.println("Conversion completed with JLayer!");
            System.out.println("Output file: " + targetFile.getAbsolutePath());
        }
    }

    This JLayer example is much shorter because mp3spi cleverly registers an MP3 decoder with JavaSound's AudioSystem. However, the underlying process is still more complex and less performant than using JAVE.

Summary: JAVE vs. JLayer

Feature JAVE (with FFmpeg) JLayer (Pure Java)
Performance Excellent (Uses native C/C++ code) Slow (Pure Java CPU loop)
Reliability High (Mature, battle-tested tool) Good, but can be tricky with edge cases
Ease of Use Very Easy (High-level API) Moderate (Requires understanding of JavaSound)
Dependencies Requires native FFmpeg binaries Pure Java JAR
Flexibility Extremely High (Can convert almost any audio/video format) Limited to formats that JLayer supports

For any serious application, JAVE is the strongly recommended choice due to its performance and reliability. The JLayer approach is only suitable for very simple, self-contained applications where adding a native dependency is not an option.

分享:
扫描分享到社交APP
上一篇
下一篇