Android 录音 与播放本地音乐功能的实现

一切尽在代码中

package rjh.yilin.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import pub.devrel.easypermissions.EasyPermissions;
import rjh.yilin.R;
import rjh.yilin.app.AppConstants;
import rjh.yilin.base.BaseActivity;
import rjh.yilin.ui.adapter.HorizontalPhotoAdapter;
import rjh.yilin.utils.LogUtils;
import rjh.yilin.utils.ObjectUtils;
import rjh.yilin.utils.ToastManager;
import rjh.yilin.utils.YiLinUtils;

/**
 * Created by 于德海 on 2018/9/4.
 * package rjh.yilin.ui.activity
 * email : [email protected]
 *
 * @describe
 */
public class TaskDetailActivity extends BaseActivity {

    private final String permission [] = new String[]{Manifest.permission.RECORD_AUDIO};

    @BindView(R.id.img_left)
    ImageView imgLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.edit_content)
    EditText editContent;
    @BindView(R.id.tv_edit_nums)
    TextView tvEditNums;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.ll_voices)
    LinearLayout llVoices;
    @BindView(R.id.img_voice)
    ImageView imgVoice;
    @BindView(R.id.tv_issue)
    TextView tvIssue;
    @BindView(R.id.tv_luyin_seconds)
    TextView tvLuyinSeconds;
    @BindView(R.id.card_luyin)
    CardView cardLuyin;
    private ArrayList mList;
    private HorizontalPhotoAdapter mAdapter;
    private Boolean is_http;
    private String tid,type;
    private MediaRecorder mMediaRecorder;
    private MediaPlayer mMediaPlayer;
    private List mRecorderList;//录音list
    @Override
    protected void initParam(Bundle param) {
        try {
            tid = param.getString("tid","");
            type = param.getString("type","");
            is_http = param.getBoolean("is_http",false);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    private int now_play_position;
    @Override
    protected int getLayoutId() {
        return R.layout.aty_task_detail;
    }

    @Override
    protected void initView() {
        mList = new ArrayList<>();
        mAdapter = new HorizontalPhotoAdapter(this);
        mAdapter.setPhotoList(mList);
        mRecorderList = new ArrayList<>();

    }

    @Override
    protected void initData() {
        tvTitle.setText("答卷");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        mRecyclerView.setAdapter(mAdapter);

    }

    @Override
    protected void initListener() {
        YiLinUtils.finishActivity(imgLeft);
        imgVoice.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()){
                        case MotionEvent.ACTION_DOWN:
                            LogUtils.e("开始录音");
                            if(EasyPermissions.hasPermissions(TaskDetailActivity.this,permission)){
                                startRecord();
                            }else {
                                ToastManager.shotToast("无权限");
                                EasyPermissions.requestPermissions(TaskDetailActivity.this,"请求录音权限",0,permission);
                            }
                            break;
                        case MotionEvent.ACTION_MOVE:
                            break;
                        case MotionEvent.ACTION_UP:
                            LogUtils.e("结束录音");
                            stopRecord();
                            break;
                        case MotionEvent.ACTION_CANCEL:
                            LogUtils.e("结束录音");
                            stopRecord();
                            break;
                    }
                return true;
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    @Override
    public void onClick(View v) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode== AppConstants.REQUEST_CODE_PICTURE&& Activity.RESULT_OK==resultCode&&data!=null){
            mList.clear();
            mList.addAll(PictureSelector.obtainMultipleResult(data));
            mAdapter.notifyDataSetChanged();
        }
    }

    private void initVoiceList(){
        llVoices.removeAllViews();
        if(mRecorderList.size()<=0)
            return;
        for (int i=0;ifinal int position = i;
            View view = LayoutInflater.from(this).inflate(R.layout.item_aty_taskdetail,llVoices,false);
            ImageView img_player = view.findViewById(R.id.img_player);
            TextView tv_second = view.findViewById(R.id.tv_seconds);
            TextView tv_delete = view.findViewById(R.id.tv_delete);
            img_player.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startplayMusic(mRecorderList.get(position));
                }
            });
            tv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mRecorderList.remove(position);
                    initVoiceList();
                }
            });
            llVoices.addView(view);
        }

    }

    //开始播放录音
    private void startplayMusic(String url){
        if(mMediaPlayer!=null){
            stopPlayMusic();
        }
            mMediaPlayer = new MediaPlayer();
        showLoading();
        try {
            mMediaPlayer.setDataSource(url);
            mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    // 装载完毕回调
                    mMediaPlayer.start();
                    dismissLoading();
                }
            });
        } catch (Exception e) {
            dismissLoading();
            ToastManager.shotToast(e.getMessage());
            e.printStackTrace();
        }
    }

    //结束录音播放
    private void stopPlayMusic(){
        if(mMediaPlayer==null)
            return;
        try {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer=null;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        if(mMediaRecorder!=null){//释放资源
            stopRecord();
        }
        if(mMediaPlayer!=null){
            stopPlayMusic();
        }
    }
    private String dir_path;
    String filePath;
    //开始录音
    private void startRecord() {
        if (mMediaRecorder == null)
            mMediaRecorder = new MediaRecorder();
        try {
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            String voice_dir = "Voice/";
            File file = new File(AppConstants.FILE_DIR+voice_dir);
            if(!file.exists()){
                file.mkdirs();
            }
            dir_path = file.getPath();
            String fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".m4a";
            filePath = dir_path + "/"+fileName;
            mMediaRecorder.setOutputFile(filePath);
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            cardLuyin.setVisibility(View.VISIBLE);
        } catch (IllegalStateException e) {
            ToastManager.shotToast(e.getMessage());
        } catch (IOException e) {
            ToastManager.shotToast(e.getMessage());
        }
    }
    //停止录音
    public void stopRecord() {
        if(mMediaRecorder==null)
            return;
        try {
            cardLuyin.setVisibility(View.GONE);
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
            mRecorderList.add(filePath);
            LogUtils.e(filePath+"");
            initVoiceList();
            filePath = "";
        } catch (RuntimeException e) {
            ToastManager.shotToast(e.getMessage());
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
            File file = new File(filePath);
            if (file.exists())
                file.delete();
            filePath = "";
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(ObjectUtils.isNotEmpty(dir_path)){
            File file = new File(dir_path);
            if(file.exists()){
                file.delete();
            }
        }
    }
}

你可能感兴趣的:(Android)