【问题标题】:How to write WAV files using ByteArrayOutputStream in Java如何在 Java 中使用 ByteArrayOutputStream 编写 WAV 文件
【发布时间】:2020-02-26 01:43:21
【问题描述】:

我正在尝试制作一个系统,它可以在不录制的情况下开始收听麦克风上的所有内容,将其存储在 ByteArrayOutputStream 对象中,当它达到某个级别时,它开始录制,当它低于所选级别时,它会再次停止录制但一直在听等等……

这是我正在使用的代码:

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

public class tests {

    protected static boolean running;
    private static ByteArrayOutputStream output;
    final static float MAX_16_BITS_SIGNED = Short.MAX_VALUE;
    final static float MAX_16_BITS_UNSIGNED = 0xffff;
    private static float level;

    private static AudioFormat getFormat() {
        return new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, false);
    }

    private static void stopAudio() {
        OutputStream wavOutput = null;
        try {
            System.out.println("Saving...");
            rinning = false;
            wavOutput = new FileOutputStream(System.getProperty("user.home") + "/Desktop/test1.wav");
            output.writeTo(wavOutput);
            System.out.println("WAV file saved. Goodbye!");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(tests.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(tests.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                wavOutput.close();
            } catch (IOException ex) {
                Logger.getLogger(tests.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private static void recordingAudio() {
        try {
            final AudioFormat format = getFormat();
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
            final TargetDataLine mic = (TargetDataLine) AudioSystem.getLine(info);
            mic.open(format);
            mic.start();
            Thread tRecording = new Thread(new Runnable() {
                int bufferLength = (int) format.getSampleRate() * format.getFrameSize();
                byte buffer[] = new byte[bufferLength];

                public void run() {
                    output = new ByteArrayOutputStream();
                    running = true;
                    while (running) {
                        int count = mic.read(buffer, 0, buffer.length);
                        calculateLevel(buffer, 0, 0);
                        int levelPercent = (int) (level * 100);
                        int gain = 50;
                        if (levelPercent > gain) {
                            output.write(buffer, 0, count);
                            System.out.println("Recording");
                        }
                    }
                    mic.stop();
                }
            });
            tRecording.start();
        } catch (LineUnavailableException e) {
            System.err.println("Line unavailable: " + e);
            System.exit(-2);
        }
    }

    private static void calculateLevel(byte[] buffer, int readPoint, int leftOver) {
        int max = 0;
        boolean signed = (getFormat().getEncoding() == AudioFormat.Encoding.PCM_SIGNED);
        boolean bigEndian = (getFormat().isBigEndian());
        for (int i = readPoint; i < buffer.length - leftOver; i += 2) {
            int value = 0;
            int hiByte = (bigEndian ? buffer[i] : buffer[i + 1]);
            int loByte = (bigEndian ? buffer[i + 1] : buffer[i]);
            if (signed) {
                short shortVal = (short) hiByte;
                shortVal = (short) ((shortVal << 8) | (byte) loByte);
                value = shortVal;
            } else {
                value = (hiByte << 8) | loByte;
            }
            max = Math.max(max, value);
        }
        if (signed) {
            level = (float) max / MAX_16_BITS_SIGNED;
        } else {
            level = (float) max / MAX_16_BITS_UNSIGNED;
        }
    }

    public static void main(String args[]) {
        recordingAudio();
        System.out.println("Stop recording press '1' + Enter");
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);

        try {
            if (br.readLine().equals("1")) {
                stopAudio();
            }
        } catch (IOException ex) {
            Logger.getLogger(pruebas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

我可以检测音频电平,只需要保存它... 在 stopAudio() 方法中,应该将 ByteArrayOutputStream 转换为 WAV 文件,它可以工作,但我不能播放它

【问题讨论】:

    标签: java bytearrayoutputstream


    【解决方案1】:

    您保存的不是 WAV 格式文件,而是原始音频数据。您需要将该数据作为 WAV 文件写入。

    虽然this question 有点过时,但仍有一些参考资料和库可能仍然可用(或者只是从某个地方找到更新的库)。

    【讨论】:

    • 音响系统没有写方法吗??!!
    • @gpasch 是吗?我已经有十多年没有接触过 Java 声音了,但我记得它使用起来很麻烦,而且链接的问题似乎没有其他说明。
    猜你喜欢
    • 2013-04-22
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多