«

android MediaRecorder录音

时间:2024-3-2 18:41     作者:韩俊     分类: Android


录音相关权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>


主程序代码:

package com.yqy.yqy_record;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

    private Button btn;
    private ListView lv;
    private SimpleAdapter adapter;
    private MediaRecorder recorder;

    private static final String RECORD_DIR = "temp_record";
    // 获得存储在外部的路径
    private File dir = new File(Environment.getExternalStorageDirectory(),
            RECORD_DIR);
    private List<Map<String, String>> records = new ArrayList<Map<String, String>>();

    private String currnetPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.recordBtn);
        lv = (ListView) findViewById(R.id.recordList);
        checkDir();
        adapter = new SimpleAdapter(this, records, R.layout.list_cell,
                new String[] { "name" }, new int[] { R.id.cell_tv });
        refreshAdapter();
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {
            @SuppressWarnings("unchecked")
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                Map<String, String> map = (Map<String, String>) adapter
                        .getItem(position);
                System.out.println(map);
                final MediaPlayer mp = MediaPlayer.create(MainActivity.this,
                        Uri.fromFile(new File(map.get("path"))));
                if(mp==null){
                    return;
                }
                mp.start();
                mp.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer arg0) {
                        mp.release();
                    }
                });
            }
        });

        btn.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    recorder = new MediaRecorder();
                    // 这边这几个方法调用的顺序不能错
                    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                    // 获得当前存放文件的地址
                    currnetPath = getPath();
                    recorder.setOutputFile(currnetPath);
                    try {
                        recorder.prepare();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    recorder.start();
                    break;
                case MotionEvent.ACTION_UP:
                    if (recorder != null) {
                        try {
                            recorder.stop();
                            refreshAdapter();
                        } catch (RuntimeException stopException) {
                            // 这个异常出现在录制之后马上停止了
                            stopException.printStackTrace();
                            File file = new File(currnetPath);
                            if (file.exists()) {
                                // 抛出异常的话就删掉错误的文件
                                file.delete();
                            }
                        }finally{
                        recorder.release();
                        recorder = null;
                        }
                    }
                    break;
                }
                return false;
            }
        });
    }

    private void checkDir() {
        if (!dir.exists()) {
            dir.mkdir();
        }
    }

    /**
     * 刷新数据
     */
    private void refreshAdapter() {
        records.clear();
        for (File file : dir.listFiles()) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("name", file.getName());
            map.put("path", file.getAbsolutePath());
            records.add(map);
        }
        adapter.notifyDataSetChanged();
    }

    @SuppressLint("SimpleDateFormat") private String getPath() {
        String name = new SimpleDateFormat("yyyyMMdd_HHmmss_SS")
                .format(new Date());
        File path = new File(dir, name + ".amr");
        return path.getAbsolutePath();
    }

}


标签: android

热门推荐