package cn.shinobi.uitl;import java.io.File;import java.io.IOException;import android.media.MediaRecorder;import android.os.Environment;public class AudioRecorder {private static int SAMPLE_RATE_IN_HZ = 8000;final MediaRecorder recorder = new MediaRecorder();final String path;public AudioRecorder(String path) {this.path = sanitizePath(path);}private String sanitizePath(String path) {if (!path.startsWith("/")) {path = "/" + path;}if (!path.contains(".")) {path += ".amr";}return Environment.getExternalStorageDirectory().getAbsolutePath()+ "/my" + path;}public void start() throws IOException {String state = android.os.Environment.getExternalStorageState();if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {throw new IOException("SD Card is not mounted,It is  " + state+ ".");}File directory = new File(path).getParentFile();if (!directory.exists() && !directory.mkdirs()) {throw new IOException("Path to file could not be created");}recorder.setAudioSource(MediaRecorder.AudioSource.MIC);recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);recorder.setAudioSamplingRate(SAMPLE_RATE_IN_HZ);recorder.setOutputFile(path);recorder.prepare();recorder.start();}public void stop() throws IOException {recorder.stop();recorder.release();}public double getAmplitude() {if (recorder != null) {return (recorder.getMaxAmplitude());} elsereturn 0;}}



package cn.shinobi.Activity;import java.io.File;import java.io.IOException;import android.annotation.SuppressLint;import android.app.Activity;import android.app.Dialog;import android.graphics.Color;import android.media.MediaPlayer;import android.media.MediaPlayer.OnCompletionListener;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.view.Gravity;import android.view.MotionEvent;import android.view.View;import android.view.View.OnClickListener;import android.view.View.OnTouchListener;import android.view.Window;import android.view.WindowManager;import android.widget.Button;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;import cn.shinobi.R;import cn.shinobi.uitl.AudioRecorder;public class RecordActivity extends Activity {private Button record;private Dialog dialog;private AudioRecorder mr;private MediaPlayer mediaPlayer;private Thread recordThread;private Button player;private TextView luyin_txt, luyin_path;private static int MAX_TIME = 15; // 最长录制时间,单位秒,0为无时间限制private static int MIX_TIME = 1; // 最短录制时间,单位秒,0为无时间限制,建议设为1private static int RECORD_NO = 0; // 不在录音private static int RECORD_ING = 1; // 正在录音private static int RECODE_ED = 2; // 完成录音private static int RECODE_STATE = 0; // 录音的状态private static float recodeTime = 0.0f; // 录音的时间private static double voiceValue = 0.0; // 麦克风获取的音量值private ImageView dialog_img;private static boolean playState = false; // 播放状态@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.record_audio);player = (Button) findViewById(R.id.player);luyin_txt = (TextView) findViewById(R.id.luyin_time);luyin_path = (TextView) findViewById(R.id.luyin_path);// 播放player.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {if (!playState) {mediaPlayer = new MediaPlayer();String url = "file:///sdcard/my/voice.amr";try {// 模拟器里播放传url,真机播放传getAmrPath()// mediaPlayer.setDataSource(url);mediaPlayer.setDataSource(getAmrPath());mediaPlayer.prepare();mediaPlayer.start();player.setText("正在播放");playState = true;// 设置播放结束时监听mediaPlayer.setOnCompletionListener(new OnCompletionListener() {@Overridepublic void onCompletion(MediaPlayer mp) {if (playState) {player.setText("播放声音");playState = false;}}});}catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}else {if (mediaPlayer.isPlaying()) {mediaPlayer.stop();playState = false;}else {playState = false;}player.setText("播放录音");}}});record = (Button) this.findViewById(R.id.record);// 录音record.setOnTouchListener(new OnTouchListener() {@SuppressLint("ClickableViewAccessibility")@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {case MotionEvent.ACTION_DOWN:// 当按下的时候开启录音操作if (RECODE_STATE != RECORD_ING) {scanOldFile();mr = new AudioRecorder("voice");RECODE_STATE = RECORD_ING;showVoiceDialog();try {mr.start();}catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}mythread();}break;case MotionEvent.ACTION_UP:if (RECODE_STATE == RECORD_ING) {RECODE_STATE = RECODE_ED;if (dialog.isShowing()) {dialog.dismiss();}try {mr.stop();voiceValue = 0.0;}catch (IOException e) {e.printStackTrace();}// 如果录音时间小于最小时if (recodeTime < MIX_TIME) {showWarnToast();record.setText("按住开始录音");RECODE_STATE = RECORD_NO;}else {record.setText("录音完成!点击重新录音");luyin_txt.setText("录音时间:" + ((int) recodeTime));luyin_path.setText("文件路径:" + getAmrPath());}}break;}return false;}});}// 删除老文件void scanOldFile() {File file = new File(Environment.getExternalStorageDirectory(), "my/voice.amr");if (file.exists()) {file.delete();}}// 录音时显示Dialogvoid showVoiceDialog() {dialog = new Dialog(RecordActivity.this, R.style.DialogStyle);dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);dialog.setContentView(R.layout.my_dialog);dialog_img = (ImageView) dialog.findViewById(R.id.dialog_img);dialog.show();}// 录音时间太短时Toast显示void showWarnToast() {Toast toast = new Toast(RecordActivity.this);LinearLayout linearLayout = new LinearLayout(RecordActivity.this);linearLayout.setOrientation(LinearLayout.VERTICAL);linearLayout.setPadding(20, 20, 20, 20);// 定义一个ImageViewImageView imageView = new ImageView(RecordActivity.this);imageView.setImageResource(R.drawable.voice_to_short); // 图标TextView mTv = new TextView(RecordActivity.this);mTv.setText("时间太短   录音失败");mTv.setTextSize(14);mTv.setTextColor(Color.WHITE);// 字体颜色// mTv.setPadding(0, 10, 0, 0);// 将ImageView和ToastView合并到Layout中linearLayout.addView(imageView);linearLayout.addView(mTv);linearLayout.setGravity(Gravity.CENTER);// 内容居中linearLayout.setBackgroundResource(R.drawable.record_bg);// 设置自定义toast的背景toast.setView(linearLayout);toast.setGravity(Gravity.CENTER, 0, 0);// 起点位置为中间 100为向下移100dptoast.show();}// 获取文件手机路径private String getAmrPath() {File file = new File(Environment.getExternalStorageDirectory(), "my/voice.amr");return file.getAbsolutePath();}// 录音计时线程void mythread() {recordThread = new Thread(ImgThread);recordThread.start();}// 录音Dialog图片随声音大小切换void setDialogImage() {if (voiceValue < 200.0) {dialog_img.setImageResource(R.drawable.record_animate_01);}else if (voiceValue > 200.0 && voiceValue < 400) {dialog_img.setImageResource(R.drawable.record_animate_02);}else if (voiceValue > 400.0 && voiceValue < 800) {dialog_img.setImageResource(R.drawable.record_animate_03);}else if (voiceValue > 800.0 && voiceValue < 1600) {dialog_img.setImageResource(R.drawable.record_animate_04);}else if (voiceValue > 1600.0 && voiceValue < 3200) {dialog_img.setImageResource(R.drawable.record_animate_05);}else if (voiceValue > 3200.0 && voiceValue < 5000) {dialog_img.setImageResource(R.drawable.record_animate_06);}else if (voiceValue > 5000.0 && voiceValue < 7000) {dialog_img.setImageResource(R.drawable.record_animate_07);}else if (voiceValue > 7000.0 && voiceValue < 10000.0) {dialog_img.setImageResource(R.drawable.record_animate_08);}else if (voiceValue > 10000.0 && voiceValue < 14000.0) {dialog_img.setImageResource(R.drawable.record_animate_09);}else if (voiceValue > 14000.0 && voiceValue < 17000.0) {dialog_img.setImageResource(R.drawable.record_animate_10);}else if (voiceValue > 17000.0 && voiceValue < 20000.0) {dialog_img.setImageResource(R.drawable.record_animate_11);}else if (voiceValue > 20000.0 && voiceValue < 24000.0) {dialog_img.setImageResource(R.drawable.record_animate_12);}else if (voiceValue > 24000.0 && voiceValue < 28000.0) {dialog_img.setImageResource(R.drawable.record_animate_13);}else if (voiceValue > 28000.0) {dialog_img.setImageResource(R.drawable.record_animate_14);}}// 录音线程private Runnable ImgThread = new Runnable() {@Overridepublic void run() {recodeTime = 0.0f;while (RECODE_STATE == RECORD_ING) {if (recodeTime >= MAX_TIME && MAX_TIME != 0) {imgHandle.sendEmptyMessage(0);}else {try {Thread.sleep(200);recodeTime += 0.2;if (RECODE_STATE == RECORD_ING) {voiceValue = mr.getAmplitude();imgHandle.sendEmptyMessage(1);}}catch (InterruptedException e) {e.printStackTrace();}}}}Handler imgHandle = new Handler() {@SuppressLint("HandlerLeak")@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 0:// 录音超过15秒自动停止if (RECODE_STATE == RECORD_ING) {RECODE_STATE = RECODE_ED;if (dialog.isShowing()) {dialog.dismiss();}try {mr.stop();voiceValue = 0.0;}catch (IOException e) {e.printStackTrace();}if (recodeTime < 1.0) {showWarnToast();record.setText("按住开始录音");RECODE_STATE = RECORD_NO;}else {record.setText("录音完成!点击重新录音");luyin_txt.setText("录音时间:" + ((int) recodeTime));luyin_path.setText("文件路径:" + getAmrPath());}}break;case 1:setDialogImage();break;default:break;}}};};public boolean dispatchKeyEvent(android.view.KeyEvent event) {System.out.println("fq activity dispatch");return super.dispatchKeyEvent(event);};}



更多相关文章

  1. Android中将assets中的文件拷贝到sd卡
  2. I2C-Tools 4.0使用说明及android平台移植,提供源码下载路径
  3. db文件查看工具SQLiteExpert
  4. android proc 虚拟文件系统
  5. Android 9 读写SD卡文件
  6. Android zip文件压缩解压缩
  7. Android studio 53 文件下载
  8. android 文件系统分析
  9. Android打开本地文件

随机推荐

  1. Android中设计具有背景图的按钮—ImageBu
  2. android背景选择器selector用法汇总
  3. Android中使用WebView, WebChromeClient
  4. Android(安卓)自动化测试—robotium(六)只
  5. Android(安卓)控制台异常:ScrollView can
  6. Android(安卓)AudioFlinger
  7. MS目录
  8. android闹钟――原代码
  9. Android(安卓)之 ServiceManager与服务管
  10. Android获取前台进程包名