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 并不能实现暂停、继续录⾳的功能
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="schemas.android/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始" />
<Button
android:id="@+id/btn_stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="停⽌" />
<TextView
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"/>
</LinearLayout>
②相关录⾳功能
开始录⾳
public void startRecord() {
/
/ 开始录⾳
/* ①Initial:实例化MediaRecorder对象 */
if (mMediaRecorder == null)
mMediaRecorder = new MediaRecorder();
try {
/* ②setAudioSource/setVedioSource */
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
/*
* ②设置输出⽂件的格式:THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式
* ,H263视频/ARM⾳频编码)、MPEG-4、RAW_AMR(只⽀持⾳频且⾳频编码要求为AMR_NB)
*/
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
/* ②设置⾳频⽂件的编码:AAC/AMR_NB/AMR_MB/Default 声⾳的(波形)的采样 */
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
fileName = DateFormat.format("yyyyMMdd_HHmmss", Instance(Locale.CHINA)) + ".m4a";
if (!FileUtils.FolderName(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 = null;
filePath = "";
} catch (RuntimeException e) {
LogUtil.String());
mMediaRecorder = null;
File file = new File(filePath);
if (ists())
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) {
getsavefilenameString 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全部代码
dia.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
hellokotlin.R;
hellokotlin.utils.FileUtils;
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 = ExternalStorageDirectory().getAbsolutePath()+"/audiodemo/"; @Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_record2);
btnStart = (Button) findViewById(R.id.btn_start);
btnStop = (Button) findViewById(R.id.btn_stop);
textTime = (TextView) findViewById(_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);
}
/**
* 开始录⾳使⽤amr格式
* 录⾳⽂件
* @return
*/
public void startRecord() {
/
/ 开始录⾳
/* ①Initial:实例化MediaRecorder对象 */
if (mMediaRecorder == null)
mMediaRecorder = new MediaRecorder();
try {
/* ②setAudioSource/setVedioSource */
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
/*
* ②设置输出⽂件的格式:THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式
* ,H263视频/ARM⾳频编码)、MPEG-4、RAW_AMR(只⽀持⾳频且⾳频编码要求为AMR_NB)
*/
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
/* ②设置⾳频⽂件的编码:AAC/AMR_NB/AMR_MB/Default 声⾳的(波形)的采样 */
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
fileName = DateFormat.format("yyyyMMdd_HHmmss", Instance(Locale.CHINA)) + ".m4a";
if (!FileUtils.FolderName(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 = null;
filePath = "";
} catch (RuntimeException e) {
LogUtil.String());
mMediaRecorder = null;
File file = new File(filePath);
if (ists())
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 实现录⾳还是⽐较简单的,只是不能暂停。
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论