AudioRecord录制音频文件并存储本地

浮躁期,太浮躁了,不能专心学习,自律,成功的人一定是自律的人。


AudioRecord录音,直接上代码:

        private int mRecordBufferSize = 0;
	private AudioRecord mRecordInstance = null;
	private ByteArrayOutputStream saveVoiceByte;
	private boolean isRecord = false;
	private static int sampleRateInHz = 16000;//采样率
	// AudioName裸音频数据文件
	private static final String AudioName = "/sdcard/raw.raw";
	// NewAudioName可播放的音频文件
	private static final String NewAudioName = "/sdcard/new.wav";

这是初始化的一些数据。


               isRecord = true;
	 new Thread(new AudioRecordThread()).start();

这是开始录音的点击事件,点击后开启一个线程,录音开识。


	if (mRecordInstance != null) {
			mRecordInstance.stop();
			mRecordInstance.release();
			mRecordInstance = null;
			isRecord = false;
		}

这是结束录音的事件,主要是释放信息。

接下来看一下录音线程中具体做了什么?

	</span>class AudioRecordThread implements Runnable {
		@Override
		public void run() {
			try {
				StartRecord();// 开始录音
				copyWaveFile(AudioName, NewAudioName);// 得到音频文件
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
	}

实现了两个方法:StartRecord和copyWaveFile,前者实现录音,后者作用是保存到本地

	public void StartRecord() {
		// TODO Auto-generated method stub
		int channelConfiguration = AudioFormat.CHANNEL_IN_MONO;
		int audioEncodingBits = AudioFormat.ENCODING_PCM_16BIT;
		mRecordBufferSize = AudioRecord.getMinBufferSize(16000, channelConfiguration, audioEncodingBits);
		mRecordInstance = new AudioRecord(MediaRecorder.AudioSource.MIC, 16000, channelConfiguration, audioEncodingBits,
				mRecordBufferSize);
		mRecordInstance.getChannelCount();
		FileOutputStream fos = null;
		File file = new File(AudioName);
		if (file.exists()) {
			file.delete();
		}
		try {
			fos = new FileOutputStream(file);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		if (mRecordInstance != null && mRecordInstance.getState() == AudioRecord.STATE_INITIALIZED) {
			try {
				mRecordInstance.startRecording();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			}
		}
		byte[] audiodata = new byte[mRecordBufferSize];
		int readsize = 0;
		try {
			saveVoiceByte = new ByteArrayOutputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		while (isRecord == true) {
			readsize = mRecordInstance.read(audiodata, 0, mRecordBufferSize);// ??
			if (AudioRecord.ERROR_INVALID_OPERATION != readsize) {
				try {
					saveVoiceByte.write(audiodata, 0, readsize);// saveVoiceByte得到的字节流
					fos.write(audiodata, 0, readsize);// 写入文件
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		try {
			saveVoiceByte.close();//
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
主要是实现录制视频,然后将原始数据保存到本地。

private void copyWaveFile(String inFilename, String outFilename) {
		FileInputStream in = null;
		FileOutputStream out = null;
		long totalAudioLen = 0;
		long totalDataLen = totalAudioLen + 36;
		long longSampleRate = sampleRateInHz;
		int channels = 1;
		long byteRate = 16 * sampleRateInHz * channels / 8;
		byte[] data = new byte[mRecordBufferSize];
		try {
			in = new FileInputStream(inFilename);
			out = new FileOutputStream(outFilename);
			totalAudioLen = in.getChannel().size();
			totalDataLen = totalAudioLen + 36;
			WriteWaveFileHeader(out, totalAudioLen, totalDataLen, longSampleRate, channels, byteRate);
			while (in.read(data) != -1) {
				out.write(data);
			}
			in.close();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 添加头信息,否则无法播放。
	 */
	private void WriteWaveFileHeader(FileOutputStream out, long totalAudioLen, long totalDataLen, long longSampleRate,
			int channels, long byteRate) throws IOException {
		byte[] header = new byte[44];
		header[0] = 'R';
		header[1] = 'I';
		header[2] = 'F';
		header[3] = 'F';
		header[4] = (byte) (totalDataLen & 0xff);
		header[5] = (byte) ((totalDataLen >> 8) & 0xff);
		header[6] = (byte) ((totalDataLen >> 16) & 0xff);
		header[7] = (byte) ((totalDataLen >> 24) & 0xff);
		header[8] = 'W';
		header[9] = 'A';
		header[10] = 'V';
		header[11] = 'E';
		header[12] = 'f';
		header[13] = 'm';
		header[14] = 't';
		header[15] = ' ';
		header[16] = 16;
		header[17] = 0;
		header[18] = 0;
		header[19] = 0;
		header[20] = 1;
		header[21] = 0;
		header[22] = (byte) channels;
		header[23] = 0;
		header[24] = (byte) (longSampleRate & 0xff);
		header[25] = (byte) ((longSampleRate >> 8) & 0xff);
		header[26] = (byte) ((longSampleRate >> 16) & 0xff);
		header[27] = (byte) ((longSampleRate >> 24) & 0xff);
		header[28] = (byte) (byteRate & 0xff);
		header[29] = (byte) ((byteRate >> 8) & 0xff);
		header[30] = (byte) ((byteRate >> 16) & 0xff);
		header[31] = (byte) ((byteRate >> 24) & 0xff);
		header[32] = (byte) (2 * 16 / 8); // block align
		header[33] = 0;
		header[34] = 16; // bits per sample
		header[35] = 0;
		header[36] = 'd';
		header[37] = 'a';
		header[38] = 't';
		header[39] = 'a';
		header[40] = (byte) (totalAudioLen & 0xff);
		header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
		header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
		header[43] = (byte) ((totalAudioLen >> 24) & 0xff);
		out.write(header, 0, 44);
	}
这个方法主要是为得到的原生视频添加头文件,否则无法播放。
Demo下载链接:点击打开链接

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,针对你的问题,我可以给出以下方案: 1. 写音频文件 使用AudioRecord录制音频数据后,可以将数据写入音频文件中,可以通过以下步骤实现: 1)创建一个FileOutputStream对象,用于指定音频文件存储路径和名称; 2)创建一个byte数组,用于存储录音数据; 3)在AudioRecord的回调函数中,将录音数据写入byte数组; 4)将byte数组写入FileOutputStream中。 示例代码如下: ``` //设置音频源(麦克风) int audioSource = MediaRecorder.AudioSource.MIC; //设置采样率 int sampleRate = 44100; //设置音频通道(单声道) int channelConfig = AudioFormat.CHANNEL_IN_MONO; //设置音频编码(PCM编码) int audioFormat = AudioFormat.ENCODING_PCM_16BIT; //计算缓冲区大小 int bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat); //创建AudioRecord对象 AudioRecord audioRecord = new AudioRecord(audioSource, sampleRate, channelConfig, audioFormat, bufferSize); //创建一个byte数组,用于存储录音数据 byte[] buffer = new byte[bufferSize]; //创建一个FileOutputStream对象,用于指定音频文件存储路径和名称 FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "audio.pcm")); //开始录音 audioRecord.startRecording(); //循环读取录音数据并写入文件 while (isRecording) { int len = audioRecord.read(buffer, 0, bufferSize); fos.write(buffer, 0, len); } //停止录音 audioRecord.stop(); //关闭FileOutputStream fos.close(); ``` 2. 获取实时麦克风音量大小 使用AudioRecord录制音频数据后,可以通过计算音量大小来获取麦克风的实时音量大小,可以通过以下步骤实现: 1)定义一个计算音量大小的方法getVolumeLevel(),用于计算音量大小; 2)在AudioRecord的回调函数中,调用getVolumeLevel()方法获取实时音量大小。 示例代码如下: ``` //定义一个计算音量大小的方法 public int getVolumeLevel(byte[] audioData) { int sum = 0; //将byte数组转换为short数组 short[] shorts = new short[audioData.length / 2]; ByteBuffer.wrap(audioData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts); //计算音量大小 for (short s : shorts) { sum += Math.abs(s); } return sum / shorts.length; } //创建一个byte数组,用于存储录音数据 byte[] buffer = new byte[bufferSize]; //开始录音 audioRecord.startRecording(); //循环读取录音数据并计算音量大小 while (isRecording) { int len = audioRecord.read(buffer, 0, bufferSize); int volumeLevel = getVolumeLevel(buffer); } //停止录音 audioRecord.stop(); ``` 以上就是实现Android AudioRecord音频文件和获取实时麦克风音量大小的方法,希望可以帮助到你。如果有任何问题或不足之处,欢迎指出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值