天天看点

android java 录音放大_Android实现录音功能实现实例(MediaRecorder)

本文介绍了Android实现录音的实例代码(MediaRecorder),分享给大家,具体如下:

Android提供了两个API用于录音的实现:MediaRecorder 和 AudioRecord,各有优劣。

1、MediaRecorder

已经集成了录音、编码、压缩等,支持少量的录音音频格式,大概有.aac(API = 16) .amr .3gp

优点:大部分已经集成,直接调用相关接口即可,代码量小

缺点:无法实时处理音频;输出的音频格式不是很多,例如没有输出mp3格式文件

2、AudioRecord

主要是实现边录边播(AudioRecord+AudioTrack)以及对音频的实时处理(如会说话的汤姆猫、语音)

优点:语音的实时处理,可以用代码实现各种音频的封装

缺点:输出是PCM语音数据,如果保存成音频文件,是不能够被播放器播放的,所以必须先写代码实现数据编码以及压缩

先说 MediaRecorder : MediaRecorder因为大部分功能已经集成,所以使用起来相对比较简单。

下面是个小demo:

① 界面

界面比较简单,由于MediaRecorder 并不能实现暂停、继续录音的功能

android:id="@+id/activity_main"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

android:id="@+id/btn_start"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="开始" />

android:id="@+id/btn_stop"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:enabled="false"

android:text="停止" />

android:id="@+id/text_time"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:text="00:00:00"

android:padding="5dp"

android:layout_marginTop="10dp"/>

② 相关录音功能

开始录音

public void startRecord() {

// 开始录音

if (mMediaRecorder == null)

mMediaRecorder = new MediaRecorder();

try {

mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风

mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".m4a";

if (!FileUtils.isFolderExist(FileUtils.getFolderName(audioSaveDir))) {

FileUtils.makeFolders(audioSaveDir);

}

filePath = audioSaveDir + fileName;

mMediaRecorder.setOutputFile(filePath);

mMediaRecorder.prepare();

mMediaRecorder.start();

} catch (IllegalStateException e) {

LogUtil.i("call startAmr(File mRecAudioFile) failed!" + e.getMessage());

} catch (IOException e) {

LogUtil.i("call startAmr(File mRecAudioFile) failed!" + e.getMessage());

}

}

音频编码可以根据自己实际需要自己设定,文件名防止重复,使用了日期_时分秒的结构,audioSaveDir 是文件存储目录,可自行设定。

停止录音

public void stopRecord() {

try {

mMediaRecorder.stop();

mMediaRecorder.release();

mMediaRecorder = null;

filePath = "";

} catch (RuntimeException e) {

LogUtil.e(e.toString());

mMediaRecorder.reset();

mMediaRecorder.release();

mMediaRecorder = null;

File file = new File(filePath);

if (file.exists())

file.delete();

filePath = "";

}

}

时长记录

// 记录录音时长

private void countTime() {

while (isRecording) {

LogUtil.d("正在录音");

timeCount++;

Message msg = Message.obtain();

msg.what = TIME_COUNT;

msg.obj = timeCount;

myHandler.sendMessage(msg);

try {

timeThread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

LogUtil.d("结束录音");

timeCount = 0;

Message msg = Message.obtain();

msg.what = TIME_COUNT;

msg.obj = timeCount;

myHandler.sendMessage(msg);

}

将录音时长格式化

// 格式化 录音时长为 时:分:秒

public static String FormatMiss(int miss) {

String hh = miss / 3600 > 9 ? miss / 3600 + "" : "0" + miss / 3600;

String mm = (miss % 3600) / 60 > 9 ? (miss % 3600) / 60 + "" : "0" + (miss % 3600) / 60;

String ss = (miss % 3600) % 60 > 9 ? (miss % 3600) % 60 + "" : "0" + (miss % 3600) % 60;

return hh + ":" + mm + ":" + ss;

}

Activity全部代码

import android.media.MediaRecorder;

import android.os.Bundle;

import android.os.Environment;

import android.os.Handler;

import android.os.Message;

import android.support.v7.app.AppCompatActivity;

import android.text.format.DateFormat;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import com.zzx.hellokotlin.R;

import com.zzx.hellokotlin.utils.FileUtils;

import com.zzx.hellokotlin.utils.LogUtil;

import java.io.File;

import java.io.IOException;

import java.util.Calendar;

import java.util.Locale;

public class Record2Activity extends AppCompatActivity {

// 录音界面相关

Button btnStart;

Button btnStop;

TextView textTime;

// 录音功能相关

MediaRecorder mMediaRecorder; // MediaRecorder 实例

boolean isRecording; // 录音状态

String fileName; // 录音文件的名称

String filePath; // 录音文件存储路径

Thread timeThread; // 记录录音时长的线程

int timeCount; // 录音时长 计数

final int TIME_COUNT = 0x101;

// 录音文件存放目录

final String audioSaveDir = Environment.getExternalStorageDirectory().getAbsolutePath()+"/audiodemo/";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_record2);

btnStart = (Button) findViewById(R.id.btn_start);

btnStop = (Button) findViewById(R.id.btn_stop);

textTime = (TextView) findViewById(R.id.text_time);

btnStart.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// 开始录音

btnStart.setEnabled(false);

btnStop.setEnabled(true);

startRecord();

isRecording = true;

// 初始化录音时长记录

timeThread = new Thread(new Runnable() {

@Override

public void run() {

countTime();

}

});

timeThread.start();

}

});

btnStop.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// 停止录音

btnStart.setEnabled(true);

btnStop.setEnabled(false);

stopRecord();

isRecording = false;

}

});

}

// 记录录音时长

private void countTime() {

while (isRecording) {

LogUtil.d("正在录音");

timeCount++;

Message msg = Message.obtain();

msg.what = TIME_COUNT;

msg.obj = timeCount;

myHandler.sendMessage(msg);

try {

timeThread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

LogUtil.d("结束录音");

timeCount = 0;

Message msg = Message.obtain();

msg.what = TIME_COUNT;

msg.obj = timeCount;

myHandler.sendMessage(msg);

}

public void startRecord() {

// 开始录音

if (mMediaRecorder == null)

mMediaRecorder = new MediaRecorder();

try {

mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风

mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".m4a";

if (!FileUtils.isFolderExist(FileUtils.getFolderName(audioSaveDir))) {

FileUtils.makeFolders(audioSaveDir);

}

filePath = audioSaveDir + fileName;

mMediaRecorder.setOutputFile(filePath);

mMediaRecorder.prepare();

mMediaRecorder.start();

} catch (IllegalStateException e) {

LogUtil.i("call startAmr(File mRecAudioFile) failed!" + e.getMessage());

} catch (IOException e) {

LogUtil.i("call startAmr(File mRecAudioFile) failed!" + e.getMessage());

}

}

public void stopRecord() {

//有一些网友反应在5.0以上在调用stop的时候会报错,翻阅了一下谷歌文档发现上面确实写的有可能会报错的情况,捕获异常清理一下就行了,感谢大家反馈!

try {

mMediaRecorder.stop();

mMediaRecorder.release();

mMediaRecorder = null;

filePath = "";

} catch (RuntimeException e) {

LogUtil.e(e.toString());

mMediaRecorder.reset();

mMediaRecorder.release();

mMediaRecorder = null;

File file = new File(filePath);

if (file.exists())

file.delete();

filePath = "";

}

}

// 格式化 录音时长为 时:分:秒

public static String FormatMiss(int miss) {

String hh = miss / 3600 > 9 ? miss / 3600 + "" : "0" + miss / 3600;

String mm = (miss % 3600) / 60 > 9 ? (miss % 3600) / 60 + "" : "0" + (miss % 3600) / 60;

String ss = (miss % 3600) % 60 > 9 ? (miss % 3600) % 60 + "" : "0" + (miss % 3600) % 60;

return hh + ":" + mm + ":" + ss;

}

Handler myHandler = new Handler() {

@Override

public void handleMessage(Message msg) {

switch (msg.what) {

case TIME_COUNT:

int count = (int) msg.obj;

LogUtil.d("count == " + count);

textTime.setText(FormatMiss(count));

break;

}

}

};

}

总结:MediaRecorder 实现录音还是比较简单的,只是不能暂停。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

继续阅读