android - 从录制的音频中去除背景噪音

标签 android audio audio-recording

我正在尝试在 android 上一次录制和播放音频。但是录制的音频有更多的噪音,如 zzzzz....

我想过滤掉音频中的噪音。我的代码是

private void record() {

    // Get the minimum buffer size required for the successful creation
    // of an AudioRecord object.
    int N = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
    audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, N * 10,
            AudioTrack.MODE_STREAM);

    AudioRecord audioRecorder = null;
    int bufferSizeInShorts;
    int shortsRead;
    short audioBuffer[];

    try {

        bufferSizeInShorts = (N / 2);

        // Initialize Audio Recorder.
        audioRecorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, N * 10);

        NoiseSuppressor.create(audioRecorder.getAudioSessionId());


        // Start Recording.
        audioBuffer = new short[bufferSizeInShorts];
        audioRecorder.startRecording();
        isRecording = true;

        audioTrack.play();
        while (isRecording) {
            shortsRead = audioRecorder.read(audioBuffer, 0, bufferSizeInShorts);

            if (shortsRead == AudioRecord.ERROR_BAD_VALUE || shortsRead == AudioRecord.ERROR_INVALID_OPERATION) {
                Log.e("record()", "Error reading from microphone.");
                isRecording = false;
                break;
            }

            audioTrack.write(audioBuffer, 0, audioBuffer.length);
        }
    } finally {
        if (audioRecorder != null) {
            audioRecorder.stop();
            audioRecorder.release();
        }

        if (audioTrack != null) {
            audioTrack.stop();
            audioTrack.release();
        }
    }
}

如何过滤背景噪音,以便我只能听到声音。

最佳答案

为了清晰和优质的语音 尝试使用 *44100 或 16000 采样率 *

注意:- 44100 采样率可能不适用于 Amulator。 还要确保你有正确的标题格式

忽略与此无关的变量

使用AudioRecord类来录音

 public class Mediarec extends Activity {

    public static final int SAMPLE_RATE = 44100;

    public static int count=0;
    private AudioRecord mRecorder;
    private File mRecording;
    private byte[] mBuffer;
    private final String startRecordingLabel = "Start recording";
    private final String stopRecordingLabel = "Stop recording";
    private boolean mIsRecording = false;
    OnGainSelected gs;
    SharedPreferences sp;
    String Shared = "Shared";
    String stored_gain;
    AudioManager am;
    protected int bitsPerSamples = 16;

    private Button show_gain;
    Switch bluetooth;
    Button button;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_mediarec);
        sp = getSharedPreferences(Shared, Context.MODE_PRIVATE);
        button = (Button) findViewById(R.id.start);
        bluetooth = (Switch) findViewById(R.id.switch1);


        initRecorder();




        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {


                    Log.d("Normal()","Recordng frm Normal MIC");
                    Normal();


            }
        });

    }

    protected void Normal() {
        // TODO Auto-generated method stub
        if (!mIsRecording ) {
            button.setText(stopRecordingLabel);
            mIsRecording = true;
            Log.d("Normal","Rec Started");
            mRecorder.startRecording();
            mRecording = getFile("raw");
            startBufferedWrite(mRecording);
        } else {
            button.setText(startRecordingLabel);
            mIsRecording = false;
            mRecorder.stop();
            File waveFile = getFile("wav");
            try {
                rawToWave(mRecording, waveFile);
            } catch (IOException e) {
                Toast.makeText(Mediarec.this, e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
            Toast.makeText(Mediarec.this, "Recorded to " + waveFile.getName(),
                    Toast.LENGTH_SHORT).show();
        }
    }



    @Override
    public void onDestroy() {
        mRecorder.release();
        super.onDestroy();
    }

    private void initRecorder() {
        int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE,
                AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
        mBuffer = new byte[bufferSize];
        mRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE,
                AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
                bufferSize);
    }

    private void startBufferedWrite(final File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                DataOutputStream output = null;
                try {
                    output = new DataOutputStream(new BufferedOutputStream(
                            new FileOutputStream(file)));
                    while (mIsRecording) {

                        int readSize = mRecorder.read(mBuffer, 0,
                                mBuffer.length);

                        for (int i = 0; i < readSize; i++) {
                            output.write(mBuffer[i]);
                        }

                    }
                } catch (IOException e) {
                    Toast.makeText(Mediarec.this, e.getMessage(),
                            Toast.LENGTH_SHORT).show();
                } finally {

                    if (output != null) {
                        try {
                            output.flush();
                        } catch (IOException e) {
                            Toast.makeText(Mediarec.this, e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        } finally {
                            try {
                                output.close();
                            } catch (IOException e) {
                                Toast.makeText(Mediarec.this, e.getMessage(),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
            }
        }).start();
    }

    private void rawToWave(final File rawFile, final File waveFile)
            throws IOException {

        byte[] rawData = new byte[(int) rawFile.length()];
        DataInputStream input = null;
        try {

            input = new DataInputStream(new FileInputStream(rawFile));
            input.read(rawData);
        } finally {
            if (input != null) {
                input.close();
            }
        }

        DataOutputStream output = null;
        try {
            output = new DataOutputStream(new FileOutputStream(waveFile));
            // WAVE header
            // see http://ccrma.stanford.edu/courses/422/projects/WaveFormat/
            writeString(output, "RIFF"); // chunk id
            writeInt(output, 36 + rawData.length); // chunk size
            writeString(output, "WAVE"); // format
            writeString(output, "fmt "); // subchunk 1 id
            writeInt(output, 16); // subchunk 1 size
            writeShort(output, (byte) 1); // audio format (1 = PCM)
            writeShort(output, (byte) 1); // number of channels
            writeInt(output, SAMPLE_RATE); // sample rate
            writeInt(output, SAMPLE_RATE * 2); // byte rate
            writeShort(output, (byte) 2); // block align
            writeShort(output, (byte) 16); // bits per sample
            writeString(output, "data"); // subchunk 2 id
            writeInt(output, rawData.length); // subchunk 2 size



            output.write(rawData);

        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_LONG)
                    .show();
        } finally {
            if (output != null) {
                output.close();
            }
        }
    }



    private File getFile(final String suffix) {
        Time time = new Time();
        time.setToNow();
        return new File(Environment.getExternalStorageDirectory(),
                time.format("%Y%m%d%H%M%S") + "." + suffix);
    }

    private void writeInt(final DataOutputStream output, final int value)
            throws IOException {
        output.write(value >> 0);
        output.write(value >> 8);
        output.write(value >> 16);
        output.write(value >> 24);
    }

    private void writeShort(final DataOutputStream output, final short value)
            throws IOException {
        output.write(value >> 0);
        output.write(value >> 8);
    }

    private void writeString(final DataOutputStream output, final String value)
            throws IOException {
        for (int i = 0; i < value.length(); i++) {
            output.write(value.charAt(i));
        }
    }


}

关于android - 从录制的音频中去除背景噪音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23888480/

相关文章:

Java - 使用 LITTLE_ENDIAN 从短到字节[2]

audio - 鸡尾酒会-音源分离

audio - 录制Nintendo 3DS/Switch音频时拆分声音效果和音乐

android - 中央按钮以编程方式和动态布局

android - 从 CLI [NativeScript] 将手持和可穿戴 Android 应用打包在一起

php - 非动态自定义HTTP header

python - 如何将 blob 文件转换为特定格式?

c# - 如何使用ASP.NET和C#将录音上传到Sound Cloud?

android - 云 Firestore : Missing or insufficient permissions

java - 使用 onPreviewFrame 运行 ML 模型