AudioRecord Class不能正确地将声音保存到文件中

时间:2016-07-22 11:45:37

标签: android audio save

美好的一天。出于个人目的,我必须使用AudioRecord类。通过这个类,我可以实时获取录制音频的字节数并根据声音显示波形。我最后需要将录音保存到文件中以.m4a格式。无论我尝试过什么,我已经尝试了所有可能的代码从谷歌搜索保存到pmc,wav,mp3,但他们都没有工作。文件保存正确,大小也正确显示,但是当我点击默认的Android媒体播放器应该播放声音的文件时,它将Toast说该文件无法播放。我假设并认为我没有正确保存它并且这个AudioRecord类一直是真正令人头痛的问题。我最后一次。你能告诉我我做错了什么吗?

这是我录制音频的活动。

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import com.ruikye.graphics.view.WaveformView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MyActivity extends Activity {
    private static final int MSG_GET_VOLUME = 0x1001;
    private WaveformView mWaveformView;
    //private GLWaveformView mGLWaveformView;
    private Handler mHandler;
    private RecordThread mRecordThread;
    private boolean isRun = false;
    private static final String AUDIO_RECORDER_FILE_EXT_WAV = "AudioRecorder.pcm";
    private static final String AUDIO_RECORDER_FOLDER = "PingBro";
    Thread runner;
    private AudioRecord ar;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopRecording();
            }
        });
        mWaveformView = (WaveformView) findViewById(R.id.waveform_view);
        //mGLWaveformView = (GLWaveformView) findViewById(R.id.gl_waveform_view);
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == MSG_GET_VOLUME) {
                    update((Float) msg.obj);
                }
                return true;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mRecordThread = new RecordThread(mHandler);
        mRecordThread.start();
        //mGLWaveformView.onResume();
    }

    @Override
    protected void onPause() {
        //mGLWaveformView.onPause();
        if (mRecordThread != null) {
            mRecordThread.pause();
            mRecordThread = null;
        }
        super.onPause();
    }

    private void update(final float volume) {
        mWaveformView.post(new Runnable() {
            @Override
            public void run() {
                mWaveformView.updateAmplitude(volume * 0.1f / 2000);
            }
        });
    }

    class RecordThread extends Thread {
        private int bs;
        private final int SAMPLE_RATE_IN_HZ = 8000;
        private Handler mHandler;

        public RecordThread(Handler handler) {
            super();
            bs = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT);
            ar = new AudioRecord(MediaRecorder.AudioSource.MIC,
                    SAMPLE_RATE_IN_HZ,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, bs);
            mHandler = handler;
        }

        public void run() {
            super.run();

            String filename = getTempFilename();
            //
            FileOutputStream os = null;
            //
            try {
                //
                os = new FileOutputStream(filename);
                //
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            ar.startRecording();
            byte[] buffer = new byte[bs];
            isRun = true;
            while (running()) {
                int r = ar.read(buffer, 0, buffer.length);
                int v = 0;
                for (byte aBuffer : buffer) {
                    v += aBuffer * aBuffer;
                }
                final double amplitude = v / r;
                try {
                    os.write(buffer, 0, bs);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.d("fsafasfasfsafas", "run: " + v * 1f / r);
                Log.d("fsafasfasfsafas", "ampliude: " + amplitude);
                Message msg = mHandler.obtainMessage(MSG_GET_VOLUME, v * 1f / r);
//                Message msg = mHandler.obtainMessage(MSG_GET_VOLUME, (float) Math.sqrt(amplitude));
                mHandler.sendMessage(msg);

            }
            ar.stop();
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public synchronized void pause() {
            isRun = false;
        }

        private synchronized boolean running() {
            return isRun;
        }

        public void start() {
            if (!running()) {
                super.start();
            }
        }
    }

    private static byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];

        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        }
        return bytes;

    }

    private static String getTempFilename() {
        // Creates the temp file to store buffer
        System.out.println("---4-1--");
        String filepath = Environment.getExternalStorageDirectory().getPath();
        System.out.println("---4-2--");
        File file = new File(filepath, AUDIO_RECORDER_FOLDER);
        System.out.println("---4-3--");

        if (!file.exists()) {
            file.mkdirs();
        }

        File tempFile = new File(filepath, AUDIO_RECORDER_FILE_EXT_WAV);
        System.out.println("---4-4--");

        if (tempFile.exists())
            tempFile.delete();
        System.out.println("---4-5--");
        return (file.getAbsolutePath() + "/" + AUDIO_RECORDER_FILE_EXT_WAV);

    }

    public void stopRecording() {
        if (null != ar) {
            isRun = false;
            ar.stop();
            ar.release();
            ar = null;
            mRecordThread = null;
        }
    }
}

0 个答案:

没有答案