Android 模仿微信长按录音功能
布局就两个button这里不多介绍了。
下面是activity内的代码
<span style="color:#808080;"></span><pre name="code" class="java">package com.example.forevercloud.myapplication;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
//语音文件保存路径
private String FileName = null;
//语音操作对象
private MediaPlayer mPlayer = null;
private MediaRecorder mRecorder = null;
private Button startRecord;
private Button startPlay;
private int isLongClick=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//开始录音
startRecord = (Button)findViewById(R.id.startRecord);
startRecord.setOnLongClickListener(new startRecordListener());
startRecord.setOnClickListener(new stopRecordListener());
//开始播放
startPlay = (Button)findViewById(R.id.startPlay);
startPlay.setOnClickListener(new startPlayListener());
//设置sdcard的路径
FileName = Environment.getExternalStorageDirectory().getAbsolutePath();
FileName += "/audio.3gp";
}
//长按录音,松开后自动执行短按操作
class startRecordListener implements View.OnLongClickListener {
@Override
public boolean onLongClick(View v) {
isLongClick = 1;
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("Audio Tag", "prepare() failed");
}
mRecorder.start();
return false; //KeyPoint:setOnLongClickListener中return的值决定是否在长按后再加一个短按动作,true为不加短按,false为加入短按
}
}
//短按停止录音,直接点击短按无效
class stopRecordListener implements View.OnClickListener {
@Override
public void onClick(View v) {
if(isLongClick==1){
mRecorder.stop();
mRecorder.release();
mRecorder = null;
isLongClick=0;
}
}
}
//播放录音
class startPlayListener implements View.OnClickListener {
@Override
public void onClick(View v) {
mPlayer = new MediaPlayer();
try{
mPlayer.setDataSource(FileName);
mPlayer.prepare();
mPlayer.start();
}catch(IOException e){
Log.e("Audio Tag","播放失败");
}
}
}
}
下面记得在mainfest.xml里添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />