录音并播放 并将录音文件导出到指定文件内

本文介绍了一款Android应用中实现录音、播放及导出功能的方法。通过使用MediaRecorder和MediaPlayer进行录音和播放操作,并利用自定义对话框选择导出路径。文章详细描述了各功能的具体实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目的:录音时,录音按钮 变为停止 播放按钮不可点击

    播放时,播放按钮变为停止,此时点击录音 则返回到上一行。播放可自动停止,可手动点击。

    上边一个TextView显示录制时长或者播放时长。不可暂停播放

    exp 可将录音文件导出至指定文件夹。

思路:

    录音:获得系统录音机,设置格式和保存录音文件,开启新线程用于记录录音时间;录音停止,释放系统录音资源。

    播放:获得系统player,获得录音文件,开启新线程用于记录播放录音时间,也要为完成事件绑定监听器。

    导出:得到当前录音文件,选择导出的地址文件,将当前录音文件中内容输入到导出的地址文件中。

源码:

RecordActivity.java:

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class RecordActivity extends Activity {


private static final String LOG_TAG = "AudioRecordTest";
private String FileName = null;


private Button startRecord;
private Button startPlay;
Button expButton;
private MediaPlayer mPlayer = null;
private MediaRecorder mRecorder = null;
private Date date;
private SimpleDateFormat sdf;


TextView textViewSound;
private long zeroTime;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


startRecord = (Button) findViewById(R.id.button_sstart);
startRecord.setText("record");
startRecord.setOnClickListener(new startRecordListener());


startPlay = (Button) findViewById(R.id.button_play);
startPlay.setText("play");
startPlay.setOnClickListener(new startPlayListener());


FileName = Environment.getExternalStorageDirectory().getAbsolutePath();
FileName += "/gadgets/record/recordsound.3gp";
File file = new File(FileName);
//file.getParentFile().getParentFile().delete();
if (!file.getParentFile().exists())
{
file.getParentFile().mkdirs();
}
textViewSound = (TextView) findViewById(R.id.textView_sound);


expButton=(Button)findViewById(R.id.button_exp);




expButton.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String string=Environment.getExternalStorageDirectory().getAbsolutePath();
new ChooseFileDialog(RecordActivity.this, new File(string), new ChooseFileDialog.CompleteChoose() {


@Override
public void finalfile(File dirFile) {
// TODO Auto-generated method stub
try {
final File f = new File(FileName);
String newpathString=dirFile.getPath()
+ "/" + System.currentTimeMillis()+".3gp";
FileCopyUtil.copyFile(f.getPath(), newpathString);
Toast.makeText(RecordActivity.this, "exp"+newpathString,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(RecordActivity.this, "exp failed",
Toast.LENGTH_SHORT).show();
}
}
}).Show();
}
});
init();
}


void init() {


Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, 1);
date = cal.getTime();
zeroTime = date.getTime();
sdf = new SimpleDateFormat("mm:ss");
textViewSound.setText("record time: " + sdf.format(date));
}


boolean isstart = false;


class startRecordListener implements OnClickListener {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!isstart || mRecorder == null) {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(FileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
isstart = true;
startRecord.setText("stop");
startPlay.setEnabled(false);
new Thread(new Runnable() {


@Override
public void run() {
// TODO Auto-generated method stub
long time = zeroTime;
while (isstart) {
date = new Date(time);
RecordActivity.this.runOnUiThread(new Runnable() {


@Override
public void run() {
// TODO Auto-generated method stub
try {


textViewSound.setText("record time: "
+ sdf.format(date));
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(RecordActivity.this,
e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
time += 1000;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
} else {
isstart = false;
mRecorder.stop();
mRecorder.release();
mRecorder = null;
startRecord.setText("record");
startPlay.setEnabled(true);
}
}


}




boolean isplay = false;


class startPlayListener implements OnClickListener {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub

if (mPlayer == null) {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(FileName);
mPlayer.prepare();
mPlayer.start();
startPlay.setText("stop");
isplay = true;

//为完成事件绑定监听器
mPlayer.setOnCompletionListener(new OnCompletionListener() {


@Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
mPlayer.release();
mPlayer = null;
startPlay.setText("play");
isplay = false;
}
});
new Thread(new Runnable() {


@Override
public void run() {
// TODO Auto-generated method stub
long time = zeroTime;
while (isplay) {
date = new Date(time);
RecordActivity.this
.runOnUiThread(new Runnable() {


@Override
public void run() {
// TODO Auto-generated method
// stub
try {


textViewSound.setText("play time: "
+ sdf.format(date));
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(
RecordActivity.this,
e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
}
});
time += 1000;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
} catch (IOException e) {
Log.e(LOG_TAG, "play wrong");
}
} else {
mPlayer.release();
mPlayer = null;
startPlay.setText("play");
isplay = false;
}
}


}

}

ChooseFileDialog.java

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;


import android.R.string;
import android.animation.AnimatorSet.Builder;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;


public class ChooseFileDialog {
Context context;
File rootFile;
File rootnow;
CompleteChoose completeChoose;


public interface CompleteChoose {
void finalfile(File dirFile);
}


public ChooseFileDialog(Context context, File rootFile,
CompleteChoose completeChoose) {
super();
this.context = context;
this.rootFile = rootFile;
rootnow = rootFile;
this.completeChoose = completeChoose;
LayoutInflater inflater = LayoutInflater.from(context);
innerView = inflater.inflate(R.layout.choosefile, null);
listView = (ListView) innerView.findViewById(R.id.choosefilelistView);
textView = (TextView) innerView.findViewById(R.id.choosetextView);


}






public void Show() {
showview();
}


android.app.AlertDialog.Builder builder;


View innerView;
TextView textView;
ListView listView;


void showview() {
builder = new AlertDialog.Builder(context).setTitle("choose exp to file")
.setPositiveButton("ok", new OnClickListener() {


@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
if(completeChoose!=null)
{
completeChoose.finalfile(rootnow);
}
}
}).setNegativeButton("no", null);
builder.setView(innerView);
builder.show();
textView.setText(rootnow.getPath());
listView.setAdapter((new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, getItemStrings(rootnow))));
listView.setOnItemClickListener(new OnItemClickListener() {


@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
rootnow = filelist.get(arg2);
listView.setAdapter((new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1,
getItemStrings(rootnow))));
textView.setText(rootnow.getPath());
}
});
}


List<File> filelist = new ArrayList<File>();
List<String> filelistStrings = new ArrayList<String>();


String[] getItemStrings(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
filelist.clear();
filelistStrings.clear();
for (File f : files) {
if (f.isDirectory()) {
filelist.add(f);
filelistStrings.add(f.getName());
}
}
String[] ss = (String[]) filelistStrings
.toArray(new String[filelistStrings.size()]);
return ss;
}
}
return new String[] {};
}


}

FileCopyUtil.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;


public class FileCopyUtil {
public static void copyFile(String oldPath, String newPath)
throws Exception {
try {
File file=new File(newPath);
if(!file.getParentFile().exists())
{
file.getParentFile().mkdirs();
}
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { // �ļ�����ʱ
InputStream inStream = new FileInputStream(oldPath); // ����ԭ�ļ�
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // �ֽ��� �ļ���С
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
// System.out.println("���Ƶ����ļ���������");
e.printStackTrace();
throw e;
}


}


public static void copyFolder(String oldpath,String newPath) throws Exception {


File a = new File(oldpath);
String[] fileStrings=a.list();
if(fileStrings!=null)
{
File temp = null;
for (int i = 0; i < fileStrings.length; i++) {
if (oldpath.endsWith(File.separator)) {
temp = new File(oldpath + fileStrings[i]);
} else {
temp = new File(oldpath + File.separator + fileStrings[i]);
}
if(temp.isDirectory())
{
copyFolder(oldpath + "/" + fileStrings[i], newPath + "/" + fileStrings[i]);
}
else {
copyFile(oldpath + "/" + fileStrings[i], newPath + "/" + fileStrings[i]);
}
}
}
}


}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.record.RecordActivity" >


    <Button
        android:id="@+id/button_exp"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:layout_alignBaseline="@+id/button_sstart"
        android:layout_alignBottom="@+id/button_sstart"
        android:layout_alignParentRight="true"
        android:layout_marginRight="22dp"
        android:text="导出" />


    <TextView
        android:id="@+id/textView_sound"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="60dp"
        android:textSize="30dp"
        android:gravity="center"
        android:text="时间: 00:00" />


    <Button
        android:id="@+id/button_play"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:layout_alignBaseline="@+id/button_sstart"
        android:layout_alignBottom="@+id/button_sstart"
        android:layout_centerHorizontal="true"
        android:text="play" />


    <Button
        android:id="@+id/button_sstart"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView_sound"
        android:layout_marginLeft="26dp"
        android:layout_marginTop="58dp"
        android:text="record" />


</RelativeLayout>

choosefile.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <TextView
        android:id="@+id/choosetextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />


    <ListView
        android:id="@+id/choosefilelistView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>


</LinearLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值