当前位置: 首页 > 面试题库 >

在Java中将mp3转换为WAV

黄聪
2023-03-14
问题内容

我将mp3转换为wav的代码是:

package audio1;

import java.io.File;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;

public class NewClass {
    public static void main(String [] args){
        try{
            AudioFileFormat inputFileFormat = AudioSystem.getAudioFileFormat(new File("c:\\1.mp3"));
            AudioInputStream ais = AudioSystem.getAudioInputStream(new File("c:\\1.mp3"));

            AudioFormat audioFormat = ais.getFormat();

            System.out.println("File Format Type: "+inputFileFormat.getType());
            System.out.println("File Format String: "+inputFileFormat.toString());
            System.out.println("File lenght: "+inputFileFormat.getByteLength());
            System.out.println("Frame length: "+inputFileFormat.getFrameLength());
            System.out.println("Channels: "+audioFormat.getChannels());
            System.out.println("Encoding: "+audioFormat.getEncoding());
            System.out.println("Frame Rate: "+audioFormat.getFrameRate());
            System.out.println("Frame Size: "+audioFormat.getFrameSize());
            System.out.println("Sample Rate: "+audioFormat.getSampleRate());
            System.out.println("Sample size (bits): "+audioFormat.getSampleSizeInBits());
            System.out.println("Big endian: "+audioFormat.isBigEndian());
            System.out.println("Audio Format String: "+audioFormat.toString());

            AudioInputStream encodedASI = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, ais);

            try{
                int i = AudioSystem.write(encodedASI, AudioFileFormat.Type.WAVE, new File("c:\\converted.wav"));
                System.out.println("Bytes Written: "+i);
            }catch(Exception e){
                e.printStackTrace();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

但是我得到以下输出:

File Format Type: MP3
File Format String: MP3 (.mp3) file, byte length: 9631340, data format: MPEG1L3 48000.0 Hz, unknown bits per sample, stereo, unknown frame size, 41.666668 frames/second, , frame length: 10030
File lenght: 9631340
Frame length: 10030
Channels: 2
Encoding: MPEG1L3
Frame Rate: 41.666668
Frame Size: -1
Sample Rate: 48000.0
Sample size (bits): -1
Big endian: true
Audio Format String: MPEG1L3 48000.0 Hz, unknown bits per sample, stereo, unknown frame size, 41.666668 frames/second, 
java.lang.ArrayIndexOutOfBoundsException: 1
        at org.tritonus.sampled.convert.javalayer.MpegFormatConversionProvider$DecodedMpegAudioInputStream$DMAISObuffer.append(MpegFormatConversionProvider.java:386)
        at javazoom.jl.decoder.Obuffer.appendSamples(Unknown Source)
        at javazoom.jl.decoder.SynthesisFilter.compute_pcm_samples(Unknown Source)
        at javazoom.jl.decoder.SynthesisFilter.calculate_pcm_samples(Unknown Source)
        at javazoom.jl.decoder.LayerIIIDecoder.decode(Unknown Source)
        at javazoom.jl.decoder.LayerIIIDecoder.decodeFrame(Unknown Source)
        at javazoom.jl.decoder.Decoder.decodeFrame(Unknown Source)
        at org.tritonus.sampled.convert.javalayer.MpegFormatConversionProvider$DecodedMpegAudioInputStream.execute(MpegFormatConversionProvider.java:307)
        at org.tritonus.share.TCircularBuffer.read(TCircularBuffer.java:138)
        at org.tritonus.share.sampled.convert.TAsynchronousFilteredAudioInputStream.read(TAsynchronousFilteredAudioInputStream.java:194)
        at javax.sound.sampled.AudioInputStream.read(AudioInputStream.java:292)
        at com.sun.media.sound.PCMtoPCMCodec$PCMtoPCMCodecStream.read(PCMtoPCMCodec.java:506)
        at com.sun.media.sound.SunFileWriter$NoCloseInputStream.read(SunFileWriter.java:199)
        at java.io.SequenceInputStream.read(SequenceInputStream.java:208)
        at java.io.SequenceInputStream.read(SequenceInputStream.java:211)
        at java.io.InputStream.read(InputStream.java:101)
        at com.sun.media.sound.WaveFileWriter.writeWaveFile(WaveFileWriter.java:247)
        at com.sun.media.sound.WaveFileWriter.write(WaveFileWriter.java:145)
        at javax.sound.sampled.AudioSystem.write(AudioSystem.java:1354)
        at audio1.NewClass.main(NewClass.java:33)

谁能帮我我在做什么错?


问题答案:
public static byte [] getAudioDataBytes(byte [] sourceBytes, AudioFormat audioFormat) throws UnsupportedAudioFileException, IllegalArgumentException, Exception{
        if(sourceBytes == null || sourceBytes.length == 0 || audioFormat == null){
            throw new IllegalArgumentException("Illegal Argument passed to this method");
        }

        ByteArrayInputStream bais = null;
        ByteArrayOutputStream baos = null;
        AudioInputStream sourceAIS = null;
        AudioInputStream convert1AIS = null;
        AudioInputStream convert2AIS = null;

        try{
            bais = new ByteArrayInputStream(sourceBytes);
            sourceAIS = AudioSystem.getAudioInputStream(bais);
            AudioFormat sourceFormat = sourceAIS.getFormat();
            AudioFormat convertFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sourceFormat.getSampleRate(), 16, sourceFormat.getChannels(), sourceFormat.getChannels()*2, sourceFormat.getSampleRate(), false);
            convert1AIS = AudioSystem.getAudioInputStream(convertFormat, sourceAIS);
            convert2AIS = AudioSystem.getAudioInputStream(audioFormat, convert1AIS);

            baos = new ByteArrayOutputStream();

            byte [] buffer = new byte[8192];
            while(true){
                int readCount = convert2AIS.read(buffer, 0, buffer.length);
                if(readCount == -1){
                    break;
                }
                baos.write(buffer, 0, readCount);
            }
            return baos.toByteArray();
        } catch(UnsupportedAudioFileException uafe){
            //uafe.printStackTrace();
            throw uafe;
        } catch(IOException ioe){
            //ioe.printStackTrace();
            throw ioe;
        } catch(IllegalArgumentException iae){
            //iae.printStackTrace();
            throw iae;
        } catch (Exception e) {
            //e.printStackTrace();
            throw e;
        }finally{
            if(baos != null){
                try{
                    baos.close();
                }catch(Exception e){
                }
            }
            if(convert2AIS != null){
                try{
                    convert2AIS.close();
                }catch(Exception e){
                }
            }
            if(convert1AIS != null){
                try{
                    convert1AIS.close();
                }catch(Exception e){
                }
            }
            if(sourceAIS != null){
                try{
                    sourceAIS.close();
                }catch(Exception e){
                }
            }
            if(bais != null){
                try{
                    bais.close();
                }catch(Exception e){
                }
            }
        }
    }

这里的sourceBytes表示MP3文件或WAV文件。audioFormat是您要转换的PCM格式。另外,我们需要将javazoom.com中的mp3spi.jar,tritonus_mp3.jar,jl * .jar,tritonus_share.jar放入类路径中。希望这对其他人有帮助。

Java 7版本:

public static byte [] getAudioDataBytes(byte [] sourceBytes, AudioFormat audioFormat) throws UnsupportedAudioFileException, IllegalArgumentException, Exception {
    if(sourceBytes == null || sourceBytes.length == 0 || audioFormat == null){
        throw new IllegalArgumentException("Illegal Argument passed to this method");
    }

    try (final ByteArrayInputStream bais = new ByteArrayInputStream(sourceBytes);
         final AudioInputStream sourceAIS = AudioSystem.getAudioInputStream(bais)) {
        AudioFormat sourceFormat = sourceAIS.getFormat();
        AudioFormat convertFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sourceFormat.getSampleRate(), 16, sourceFormat.getChannels(), sourceFormat.getChannels()*2, sourceFormat.getSampleRate(), false);
        try (final AudioInputStream convert1AIS = AudioSystem.getAudioInputStream(convertFormat, sourceAIS);
             final AudioInputStream convert2AIS = AudioSystem.getAudioInputStream(audioFormat, convert1AIS);
             final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte [] buffer = new byte[8192];
            while(true){
                int readCount = convert2AIS.read(buffer, 0, buffer.length);
                if(readCount == -1){
                    break;
                }
                baos.write(buffer, 0, readCount);
            }
            return baos.toByteArray();
        }
    }
}

Maven:

<dependency>
    <groupId>com.googlecode.soundlibs</groupId>
    <artifactId>mp3spi</artifactId>
    <version>1.9.5-1</version>
</dependency>
<dependency>
    <groupId>com.googlecode.soundlibs</groupId>
    <artifactId>jlayer</artifactId>
    <version>1.0.1-1</version>
    <exclusions>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
</dependency>


 类似资料:
  • 问题内容: 我在Java方面苦苦挣扎,但无法将Java .wav转换为.mp3转换器的有效示例。该转换器将在Java applet中使用,因此它应仅依赖以纯Java编写的库,而无需底层C代码调用。 谁能提供一个完整的示例? 谢谢 问题答案: 阅读您的wave文件@ http://java.sun.com/javase/technologies/desktop/media/jmf/ 并编码为mp3

  • 问题内容: 我正在使用SimpleLameLibForAndroid将使用android中的AudioRecord类创建的pcm文件转换为mp3。我读取了pcm文件并将其编码为mp3,然后将其写入文件中。结果为mp3文件,但不正确,上面有很多噪音,很难理解它是录制的pcm文件。这些是录制的音频规范(pcm文件): 这是我的代码,它使用liblame编码mp3并将其写入文件: 我该如何解决此代码,b

  • 问题内容: 这里有人知道在Java中将csv文件转换为xls或xlsx文件的任何快速,干净的方法吗? 我已经有一些东西可以管理csv文件,并且我需要与其他程序具有额外的兼容性。 除了包名称外,示例代码始终受到人们的赞赏。 非常感谢, 贾斯汀 到目前为止,这是我的代码。我需要从行中删除返回值(“ \ n”)。我的某些单元格包含多行信息(一个列表),因此我可以在csv中使用“ \ n”来表示 单元格中

  • 问题内容: 我有一个GMT字段,用户在其中输入要转换为IST的时间(例如:小时字段18,分钟字段30,会话字段am / pm)。我需要获取这些输入并在Java中转换为IST ??? 问题答案: 如果您意识到时区仅与格式化为String的日期相关,则这是非常容易且显而易见的-秒/毫秒时间戳(仅是包装器)始终是隐式UTC(正确地称为GMT)。而且,在这种时间戳和字符串之间进行转换始终会同时使用时区。

  • 问题内容: 如何在Java中将(2个字节)转换为字节数组,例如 应该是这样的。但不确定。 编辑: 您也可以使用: 发现以获取本机位顺序是大还是小。另外,从以下代码中提取代码: 字节(数组/偏移量)为布尔值 字节数组到char 字节数组短 字节数组到int 浮动的字节数组 字节数组长 字节数组加倍 反之亦然。 问题答案:

  • 问题内容: 如何在Java中将bmp转换为jpg?我知道如何使用该方法,但是有更快或更更好的方法吗? 这是我在网上找到的ImageIO的处理方式。 如果使用这种方式,我会失去质量吗? 谢谢 问题答案: 是的你将会。实际上,无论将BMP(无损)转换为JPG(有损)的方式如何,始终会失去质量。如果将JPG质量设置为100%(在我看来这违背了目的),则可以限制损坏。 使用本教程修复它。