MediaRecorder和MediaPlayer的简单使用

public class SimpleRecorderActivity extends Activity{

	private static final String SOUND_FILE_NAME = "/sound";
	private ListView mListView;
	private Button mStartBtn;
	private Button mStopBtn;
	private MediaRecorder mAudioRecorder;
	private MediaPlayer mAudioPlayer;
	private String mSoundDirPath;
	private File[] mSoundFiles;
	private int mListLength;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_simple_recorder);
		
		init();
	}

	
	/**
	 * 初始化界面
	 */
	private void init() {
		if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			Toast.makeText(SimpleRecorderActivity.this, "SD卡不存在,请插入SD卡!", Toast.LENGTH_SHORT).show();
			return;
		}
		//获得录音保存路径
		mSoundDirPath = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ Consts.FOOLISH_PATH + Consts.FOOLISH_SOUND_PATH;
				
		initListView();
		mStartBtn = (Button)findViewById(R.id.btn_simple_recorder_start);
		mStartBtn.setOnClickListener(onClickListener);
		mStopBtn = (Button)findViewById(R.id.btn_simple_recorder_stop);
		mStopBtn.setOnClickListener(onClickListener);
	}
	
	
	/**
	 * 初始化列表
	 */
	private void initListView() {
		mListView = (ListView)findViewById(R.id.lv_simple_recorder);
		List<String> list = getData(new File(mSoundDirPath));
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SimpleRecorderActivity.this, 
				android.R.layout.simple_list_item_1, 
				list); 
		mListView.setAdapter(arrayAdapter);
		mListView.setOnItemClickListener(new onItemClickListener());
		mListLength = mListView.getCount();
		
	}
	
	
	/**
	 * 遍历目录
	 * @param file
	 * @return
	 */
	private List<String> getData(File file) {
		List<String> list = new ArrayList<String>(); 
		mSoundFiles = file.listFiles();
		for(int i=0; i<mSoundFiles.length; i++) {
			if(!mSoundFiles[i].isDirectory()) {
				list.add(mSoundFiles[i].getName());
			}
		}
		return list;
	}
	
	
	/**
	 * 开始录音
	 */
	private void startRecorder() {
		try {
			mAudioRecorder = new MediaRecorder();
			//设置MediaRecorder的音频源为麦克风
			mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			//设置MediaRecorder录制的音频格式
			mAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			//设置MediaRecorder录制音频的编码为AMR
			mAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			//设置录制好的音频文件保存路径
			mAudioRecorder.setOutputFile(getSoundFile(mSoundDirPath, SOUND_FILE_NAME + mListLength + ".amr").getAbsolutePath());
			//准备录制
			mAudioRecorder.prepare();
			//开始录制
			mAudioRecorder.start();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//只允许点击停止按钮
		mStartBtn.setEnabled(false);
		mStopBtn.setEnabled(true);
		mListView.setEnabled(false);
	}
	
	
	/**
	 * 停止录音
	 */
	private void stopRecorder() {
		if(mAudioRecorder != null) {
			mAudioRecorder.stop();
			mAudioRecorder.release();
			mAudioRecorder = null;
			//只允许点击开始按钮
			mStartBtn.setEnabled(true);
			mStopBtn.setEnabled(false);
			mListView.setEnabled(true);
		}
	}
	
	
	/**
	 * 获得音频文件
	 * @param dirpath
	 * @param filename
	 * @return
	 */
	private File getSoundFile(String dirpath, String filename) {
		File dir = null;
		File file = null;
		try {
			//创建目录
			dir = new File(dirpath);
			if(!dir.exists() || !dir.isDirectory()) {
				dir.mkdirs();
			}
			//创建文件
			file = new File(dirpath + filename);
			if(!file.exists()) {
				file.createNewFile();
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return file;
	}
	
	
	private View.OnClickListener onClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_simple_recorder_start:
				startRecorder();
				break;

			case R.id.btn_simple_recorder_stop:
				stopRecorder();
				initListView();
				break;
			}
			
		}
	};
	
	
	private class onItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if(mSoundFiles.length <= position) {
				return;
			}
			try {
				String filepath = mSoundFiles[position].getAbsolutePath();
				//创建一个MediaPlayer去播放指定音频文件
				mAudioPlayer = new MediaPlayer();
				mAudioPlayer.setDataSource(filepath);
				mAudioPlayer.prepare();
				mAudioPlayer.start();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			//显示一个对话框,告知哪个音频文件正在播放
			AlertDialog.Builder builder = new AlertDialog.Builder(SimpleRecorderActivity.this);
			builder.setMessage(mSoundFiles[position].getName() + "正在播放...")
				.setPositiveButton("停止", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(mAudioPlayer != null && mAudioPlayer.isPlaying()) {
							mAudioPlayer.stop();
						}
					}
				}).create();
			final Dialog dialog = builder.show();
			
			//当音频文件播放完毕后,对话框自动关闭
			mAudioPlayer.setOnCompletionListener(new OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					mp.release();
					dialog.dismiss();
				}
			});
		}
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		stopRecorder();	
		if(mAudioPlayer != null) {
			mAudioPlayer.release();
			mAudioPlayer = null;
		}
	};
}

发布了73 篇原创文章 · 获赞 31 · 访问量 29万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览