Android 开发之录音与播放

项目中可能有这样的需求:就是录音留言。今天针对这个写了这篇博客。
效果图:

Android 开发之录音与播放_第1张图片

文末会贴出项目下载地址,可以前去下载。。。

1,添加权限

<uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_LOGS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.VIBRATE" />

2,看布局文件


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="horizontal"
    android:background="@drawable/main_layout_bg"
    tools:context="com.gyq.recorddemo.MainActivity">


    <Button
        android:id="@+id/btn_voice_reset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/icon_rerecord_nor"
        android:textColor="#ffffff"
        android:textSize="18sp"
        android:text="重录"/>
   <LinearLayout
       android:id="@+id/ll_recording"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:gravity="center"
       android:layout_marginLeft="20dp"
       android:orientation="vertical">
       <ImageView
           android:id="@+id/iv_voice"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/icon_record_nor"/>

       <Chronometer
           android:id="@+id/chr_timer"
           android:layout_marginTop="8dp"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textSize="16sp"
           android:textColor="#ff0000"/>
       <TextView
           android:id="@+id/tv_click_status"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginTop="12dp"
           android:textSize="18sp"
           android:textColor="#ffffff"
           android:text="点击开始录音"/>
   LinearLayout>

    <Button
        android:id="@+id/btn_voice_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:background="@drawable/icon_clean_nor"
        android:textColor="#ffffff"
        android:textSize="18sp"
        android:text="清除"/>
LinearLayout>

3,逻辑代码(代码中,有相应的注释)

package com.gyq.recorddemo;

import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout mRecord;
    private ImageView mVoice;
    private TextView mStatus;
    private Chronometer mTimer;

    private File mRecAudioFile;        // 录制的音频文件
    private File mRecAudioPath;        // 录制的音频文件路徑
    private MediaRecorder mMediaRecorder;// MediaRecorder对象

    private String strTempFile = "recaudio_";// 零时文件的前缀

    private String voicePath;

    private Button mBtnReset;
    private Button mBtnDelete;


    private int flag = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        /* 检测是否存在SD卡 */
        if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        {
            mRecAudioPath = Environment.getExternalStorageDirectory();// 得到SD卡得路径
        } else
        {
            Toast.makeText(MainActivity.this, "没有SD卡", Toast.LENGTH_LONG).show();
        }




    }

    private void initView() {
        mRecord = (LinearLayout)findViewById(R.id.ll_recording);
        mVoice = (ImageView)findViewById(R.id.iv_voice);
        mStatus = (TextView)findViewById(R.id.tv_click_status);
        mTimer = (Chronometer)findViewById(R.id.chr_timer);

        mBtnReset = (Button)findViewById(R.id.btn_voice_reset);
        mBtnDelete = (Button)findViewById(R.id.btn_voice_delete);
        mBtnReset.setVisibility(View.GONE);
        mBtnDelete.setVisibility(View.GONE);

        mRecord.setOnClickListener(this);
        mBtnDelete.setOnClickListener(this);
        mBtnReset.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.ll_recording :
                if (flag == 0) {
                    mVoice.setImageResource(R.drawable.icon_record_moving);
                    mStatus.setText("点击停止录音");
                    mTimer.setVisibility(View.VISIBLE);
                    mTimer.setBase(SystemClock.elapsedRealtime());
                    mTimer.start();

                    try
                    {
                    /* ①Initial:实例化MediaRecorder对象 */
                        mMediaRecorder = new MediaRecorder();
                    /* ②setAudioSource/setVedioSource*/
                        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置麦克风
                    /* ②设置输出文件的格式:THREE_GPP/MPEG-4/RAW_AMR/Default
                     * THREE_GPP(3gp格式,H263视频/ARM音频编码)、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB)
                     * */
                        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                    /* ②设置音频文件的编码:AAC/AMR_NB/AMR_MB/Default */
                        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                    /* ②设置输出文件的路径 */
                        try
                        {
                            mRecAudioFile = File.createTempFile(strTempFile, ".mp4", mRecAudioPath);

                            voicePath = mRecAudioPath + "/" + strTempFile + System.currentTimeMillis() + ".mp4";


                        } catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                        mMediaRecorder.setOutputFile(mRecAudioFile.getAbsolutePath());
                    /* ③准备 */
                        mMediaRecorder.prepare();
                    /* ④开始 */
                        mMediaRecorder.start();
                    /*按钮状态*/
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }

                }else if (flag == 1){
                    mVoice.setImageResource(R.drawable.icon_record_on);
                    mStatus.setText("点击试听");
                    mTimer.stop();

                    // TODO Auto-generated method stub
                    if (mRecAudioFile != null)
                    {
                    /* ⑤停止录音 */
                        mMediaRecorder.stop();
                    /* ⑥释放MediaRecorder */
                        mMediaRecorder.release();
                        mMediaRecorder = null;
                    }
                }else if (flag == 2) {
                    //mVoice.setImageResource(R.drawable.icon_record_nor);
                    //mStatus.setText("点击开始录音");
                    mBtnReset.setVisibility(View.VISIBLE);
                    mBtnDelete.setVisibility(View.VISIBLE);
                    mTimer.stop();
                    mTimer.setVisibility(View.GONE);

                    mRecord.setEnabled(false);

                    /* 得到被点击的文件 */

                    Log.d("haha", "onClick: " +voicePath);
                    playMusic(mRecAudioFile);


                }

                flag = (flag + 1) % 3;

                break;

            case R.id.btn_voice_reset :
                flag = 0;
                mVoice.setImageResource(R.drawable.icon_record_nor);
                mStatus.setText("点击开始录音");
                mRecord.setEnabled(true);
                mBtnReset.setVisibility(View.GONE);
                mBtnDelete.setVisibility(View.GONE);
                break;

            case R.id.btn_voice_delete :
                if (mRecAudioFile == null) {
                    return;
                }

                mRecAudioFile.delete();
                Toast.makeText(MainActivity.this,"录音已删除",Toast.LENGTH_SHORT).show();
                break;

            default:

                break;
        }
    }

    /* 播放录音文件 */
    private void playMusic(File  file)
    {
        MediaPlayer player = new MediaPlayer();
        try {
            player.setDataSource(file.getPath());
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

项目地址:RecordDemo

你可能感兴趣的:(Android,基础)