杰瑞科技汇

Java如何实现WAV转MP3?

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

Java如何实现WAV转MP3?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the most popular and robust library, JAVE (Java Audio Video Encoder), and an alternative, LAME.

Summary of Approaches

Method Library Pros Cons Best For
JAVE (Recommended) ws.schild:jave-all-deps Very easy to use, single dependency, handles many formats. Can be large, underlying FFmpeg version might be slightly older. Quick and easy conversions without complex configuration.
LAME com.github.lame:lame High-quality, small output file, actively maintained LAME encoder. More complex setup (requires native .dll/.so files), more verbose code. High-quality audio encoding where file size and quality are critical.

Method 1: Using JAVE (Java Audio Video Encoder)

JAVE is a Java wrapper around the powerful FFmpeg command-line tool. It makes conversion incredibly simple by providing a clean Java API.

Step 1: Add the Dependency

You need to add the JAVE dependency to your project. The jave-all-deps version is the easiest as it bundles all the necessary native libraries.

For Maven (pom.xml):

Java如何实现WAV转MP3?-图2
(图片来源网络,侵删)
<dependency>
    <groupId>ws.schild</groupId>
    <artifactId>jave-all-deps</artifactId>
    <version>3.3.1</version> <!-- Check for the latest version on Maven Central -->
</dependency>

For Gradle (build.gradle):

implementation 'ws.schild:jave-all-deps:3.3.1' // Check for the latest version

Step 2: Write the Java Code

The code is straightforward. You create an AudioAttributes object to define the MP3's properties (like bitrate and channel type) and an EncodingAttributes object to specify the source and target formats.

import ws.schild.jave.*;
import java.io.File;
public class WavToMp3Converter {
    public static void main(String[] args) {
        // Define input and output files
        File source = new File("input.wav");
        File target = new File("output.mp3");
        try {
            // 1. Set audio attributes (quality, bitrate, channels, sample rate)
            AudioAttributes audio = new AudioAttributes();
            audio.setCodec("libmp3lame"); // Use the LAME codec for MP3
            audio.setBitRate(128000);     // Bitrate in bits per second (e.g., 128 kbps)
            audio.setChannels(2);          // 1 for mono, 2 for stereo
            audio.setSamplingRate(44100);  // Sample rate in Hz
            // 2. Set encoding attributes (format, start time, duration)
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setFormat("mp3");
            attrs.setAudioAttributes(audio);
            // 3. Create an encoder and perform the conversion
            System.out.println("Starting conversion...");
            Encoder encoder = new Encoder();
            encoder.encode(new MultimediaObject(source), target, attrs);
            System.out.println("Conversion complete! Output file: " + target.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How to Run

  1. Make sure you have input.wav in the same directory as your compiled Java class, or provide the full path.
  2. Run the main method.
  3. You will find output.mp3 in the same directory.

Method 2: Using LAME Directly (More Control)

This method uses a pure Java wrapper for the LAME encoder, which is widely considered the gold standard for MP3 encoding. This gives you more control over the encoding process and potentially higher quality.

Step 1: Add the Dependency

For Maven (pom.xml):

Java如何实现WAV转MP3?-图3
(图片来源网络,侵删)
<dependency>
    <groupId>com.github.lame</groupId>
    <artifactId>lame</artifactId>
    <version>3.100</version> <!-- Check for the latest version -->
</dependency>

Note: This library requires the native LAME libraries. The Maven dependency usually handles downloading them, but you might need to configure your IDE or build tool to find them correctly.

Step 2: Write the Java Code

This approach is more low-level. You'll read the WAV file, process its audio data in chunks, and feed it to the LAME encoder.

import com.github.lame.encoder.LameEncoder;
import com.github.lame.encoder.MP3AudioFormat;
import com.github.lame.encoder.MP3AudioInputStream;
import javax.sound.sampled.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WavToMp3LameConverter {
    public static void main(String[] args) {
        File source = new File("input.wav");
        File target = new File("output_lame.mp3");
        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(source);
             FileOutputStream fos = new FileOutputStream(target)) {
            // Get format from the WAV file
            AudioFormat wavFormat = audioInputStream.getFormat();
            System.out.println("Source WAV Format: " + wavFormat);
            // Define the target MP3 format
            // LAME requires a specific MP3 format with MPEG LAYER III encoding
            AudioFormat mp3Format = new AudioFormat(
                    AudioFormat.Encoding.MPEG1L3,
                    wavFormat.getSampleRate(),
                    16, // Bit depth is typically 16 for LAME input
                    wavFormat.getChannels(),
                    wavFormat.getChannels() * 2, // Frame size
                    wavFormat.getFrameRate(),
                    false // Big-endian
            );
            // Create an MP3 audio input stream using LAME
            MP3AudioInputStream mp3AudioInputStream = new MP3AudioInputStream(
                    new LameEncoder(
                            wavFormat,
                            mp3Format,
                            128 // Bitrate in kbps
                    ),
                    audioInputStream
            );
            // Write the encoded MP3 data to the output file
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = mp3AudioInputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            System.out.println("Conversion complete! Output file: " + target.getAbsolutePath());
        } catch (UnsupportedAudioFileException | IOException e) {
            e.printStackTrace();
        }
    }
}

Key Concepts Explained

  1. Bitrate (setBitRate): This is the most important factor for MP3 quality and file size.

    • 128 kbps: Good quality, standard for many applications.
    • 192 kbps: High quality, a good balance for most music.
    • 320 kbps: Near-lossless quality, but results in larger files.
  2. Channels (setChannels):

    • 1 for Mono.
    • 2 for Stereo. The converter will automatically downmix stereo WAVs to mono if you set channels to 1.
  3. Sample Rate (setSamplingRate):

    • The standard for CD-quality audio is 44100 Hz.
    • If your source WAV has a different sample rate, you can either keep it or resample it. For best quality, match it to the source or use a standard rate like 44100.
  4. Why not use the standard Java Sound API?

    • The javax.sound.sampled package can read WAV files and write them to other formats (like AU), but it cannot encode to compressed formats like MP3. It lacks the necessary codec libraries.

Troubleshooting

  • java.lang.UnsatisfiedLinkError: no jave in java.library.path (JAVE)
    • This means the native FFmpeg libraries can't be found. The jave-all-deps JAR usually includes them. If you're running from an IDE (like IntelliJ or Eclipse), make sure the IDE is configured to extract the native libraries from the JAR and include them in the runtime classpath.
  • java.lang.NoClassDefFoundError (LAME)
    • Ensure you have added the lame dependency correctly. This error usually means the build tool (Maven/Gradle) hasn't downloaded the JAR to your local repository.
  • Poor Audio Quality

    Increase the bitrate. A bitrate of 128 kbps might be too low for high-quality source audio. Try 192 or 320 kbps.

  • Conversion Fails

    Double-check that your input WAV file is not corrupted and is a valid format that the library supports.

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