package com.app.recordingtest; import java.io.File; import java.io.IOException; import android.app.Activity; import android.media.MediaRecorder; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; /** * v1.0 version * * @author Administrator * */ public class MainActivity extends Activity implements OnClickListener { Button button1, button2; MediaRecorder recorder; ListView listView1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); listView1 = (ListView) findViewById(R.id.listView1); button1.setOnClickListener(this); button2.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1 : try { begin(); } catch (IOException e) { e.printStackTrace(); } break; case R.id.button2 : stop(); break; default : break; } } private void stop() { recorder.stop(); // 暂停 recorder.reset(); // 重置 recorder.release(); // 释放 Toast.makeText(MainActivity.this, "暂停..", Toast.LENGTH_SHORT).show(); } private void begin() throws IOException { final String PATH = "/mnt/sdcard"; // 设置路径 File filePath = new File(PATH); filePath = File.createTempFile("/fileName", ".amr/", filePath); String outPath = filePath.getPath().toString(); Toast.makeText(MainActivity.this, "开始.." + outPath, Toast.LENGTH_SHORT) .show(); recorder = new MediaRecorder(); // 创建对象 recorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 设置来源 recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // 设置输出格式 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 设置编码 recorder.setOutputFile(outPath); // 设置输出路径 Toast.makeText(MainActivity.this, " .." + filePath.getAbsolutePath().toString(), Toast.LENGTH_SHORT).show(); try { recorder.prepare(); // 准备录音 recorder.start(); // 开始录音 Toast.makeText(MainActivity.this, "开始..", Toast.LENGTH_SHORT) .show(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }