簡體   English   中英

如何使用 Java 中的 ByteArrayOutputStream 編寫 WAV 文件

[英]How to write WAV files using ByteArrayOutputStream in Java

我正在嘗試制作一個系統,該系統可以在不錄制的情況下開始收聽麥克風上的所有內容,並將其存儲在 ByteArrayOutputStream object 中,當它達到某個級別時,它開始錄制,當它低於所選級別時,它會再次停止錄制但繼續收聽等等...

這是我正在使用的代碼:

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 文件,它可以工作,但我不能播放它

您保存的不是 WAV 格式文件,而是原始音頻數據。 需要將該數據寫入 WAV 文件。

雖然這個問題有點過時,但有一些參考資料和庫可能仍然可用(或者只是從某個地方找到更新的庫)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM