Android realizes voice playback and recording function

  • 2021-09-16 07:55:40
  • OfStack

In this paper, we share the specific codes of Android to realize voice playing and recording for your reference. The specific contents are as follows

Technical points and highlights used in the project

Voice recordings (single and list) Voice playback (single and list) Voice recording package Voice player package Sequential playback of voice list Treatment of single play multiplexing problem of speech list

Since the mp3 format file cannot be recorded while the mp3 format is common to Android and ios, we need to be able to directly record the mp3 file or convert the recorded format to mp3 format

Adding this library below can directly record mp3 files, which I think is the most convenient

compile 'com. czt. mp3recorder: library: 1.0. 3'

1. Voice recording package

The code is simple. See for yourself


package com.video.zlc.audioplayer;

import com.czt.mp3recorder.MP3Recorder;
import com.video.zlc.audioplayer.utils.LogUtil;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
 * @author zlc
 */
public class AudioManage {

 private MP3Recorder mRecorder;
 private String mDir;    //  Name of the folder 
 private String mCurrentFilePath;
 private static AudioManage mInstance;

 private boolean isPrepared; //  Identification MediaRecorder Ready 
 private AudioManage(String dir) {
  mDir = dir;
  LogUtil.e("AudioManage=",mDir);
 }

 /**
  *  Callback "ready" 
  * @author zlc
  */
 public interface AudioStateListenter {
  void wellPrepared(); // prepared Over 
 }

 public AudioStateListenter mListenter;

 public void setOnAudioStateListenter(AudioStateListenter audioStateListenter) {
  mListenter = audioStateListenter;
 }

 /**
  *  Use singleton to implement  AudioManage
  * @param dir
  * @return
  */
 public static AudioManage getInstance(String dir) {
  if (mInstance == null) {
   synchronized (AudioManage.class) { //  Synchronization 
    if (mInstance == null) {
     mInstance = new AudioManage(dir);
    }
   }
  }
  return mInstance;
 }

 /**
  *  Prepare for recording 
  */
 public void prepareAudio() {

  try {
   isPrepared = false;
   File dir = new File(mDir);
   if (!dir.exists()) {
    dir.mkdirs();
   }
   String fileName = GenerateFileName(); //  File name 
   File file = new File(dir, fileName); //  Path + File name 
   //MediaRecorder Recording and video recording can be realized. Need to be strictly observed API The sequence of function calls in the description .
   mRecorder = new MP3Recorder(file);
   mCurrentFilePath = file.getAbsolutePath();
//   mMediaRecorder = new MediaRecorder();
//   mCurrentFilePath = file.getAbsolutePath();
//   mMediaRecorder.setOutputFile(file.getAbsolutePath()); //  Set the output file 
//   mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //  Settings MediaRecorder The audio source of is a microphone 
//   mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); //  Format audio 
//   mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); //  Set the audio encoding to AMR_NB
//   mMediaRecorder.prepare();
//   mMediaRecorder.start();
   mRecorder.start(); // Start recording 
   isPrepared = true; //  Ready to finish 
   if (mListenter != null) {
    mListenter.wellPrepared();
   }
  } catch (Exception e) {
   e.printStackTrace();
   LogUtil.e("prepareAudio",e.getMessage());
  }

 }

 /**
  *  Randomly generate file names 
  * @return
  */
 private String GenerateFileName() {
  // TODO Auto-generated method stub
  return UUID.randomUUID().toString() + ".mp3"; //  Audio file format 
 }


 /**
  *  Get the volume level-through mMediaRecorder Get the amplitude and convert it to sound Level
  * maxLevel Maximum 7 ; 
  * @return
  */
 public int getVoiceLevel(int maxLevel) {
  if (isPrepared) {
   try {
    mRecorder.getMaxVolume();
    return maxLevel * mRecorder.getMaxVolume() / 32768 + 1;
   } catch (Exception e) {
     e.printStackTrace();
   }
  }
  return 1;
 }

 /**
  *  Release resources 
  */
 public void release() {
  if(mRecorder != null) {
   mRecorder.stop();
   mRecorder = null;
  }
 }

 /**
  *  Stop recording 
  */
 public void stop(){
  if(mRecorder!=null && mRecorder.isRecording()){
   mRecorder.stop();
  }
 }

 /**
  *  Cancel (release resource + Delete a file) 
  */
 public void delete() {
  release();
  if (mCurrentFilePath != null) {
   File file = new File(mCurrentFilePath);
   file.delete(); // Delete a recording file 
   mCurrentFilePath = null;
  }
 }

 public String getCurrentFilePath() {
  return mCurrentFilePath;
 }

 public int getMaxVolume(){
  return mRecorder.getMaxVolume();
 }

 public int getVolume(){
  return mRecorder.getVolume();
 }
}

2. Voice Player Packaging


package com.video.zlc.audioplayer.utils;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;

/**
 *
 * @author zlc
 *
 */
public class MediaManager {

 private static MediaPlayer mMediaPlayer; // Play a recording file 
 private static boolean isPause = false;

 static {
  if(mMediaPlayer==null){
   mMediaPlayer=new MediaPlayer();
   mMediaPlayer.setOnErrorListener( new MediaPlayer.OnErrorListener() {

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
     mMediaPlayer.reset();
     return false;
    }
   });
  }
 }


 /**
  *  Play audio 
  * @param filePath
  * @param onCompletionListenter
  */
 public static void playSound(Context context,String filePath, MediaPlayer.OnCompletionListener onCompletionListenter){

  if(mMediaPlayer==null){
   mMediaPlayer = new MediaPlayer();
   mMediaPlayer.setOnErrorListener( new MediaPlayer.OnErrorListener() {
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
     mMediaPlayer.reset();
     return false;
    }
   });
  }else{
   mMediaPlayer.reset();
  }
  try {
   // See " MediaPlayer "Call procedure diagram 
   mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
   mMediaPlayer.setOnCompletionListener(onCompletionListenter);
   mMediaPlayer.setDataSource(filePath);
   mMediaPlayer.prepare();
   mMediaPlayer.start();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   LogUtil.e(" Voice error==",e.getMessage());
  }
 }


 /**
  *  Suspend 
  */
 public synchronized static void pause(){
  if(mMediaPlayer!=null && mMediaPlayer.isPlaying()){
   mMediaPlayer.pause();
   isPause=true;
  }
 }

 // Stop 
 public synchronized static void stop(){
  if(mMediaPlayer!=null && mMediaPlayer.isPlaying()){
   mMediaPlayer.stop();
   isPause=false;
  }
 }

 /**
  * resume Continue 
  */
 public synchronized static void resume(){
  if(mMediaPlayer!=null && isPause){
   mMediaPlayer.start();
   isPause=false;
  }
 }

 public static boolean isPause(){
  return isPause;
 }

 public static void setPause(boolean isPause) {
  MediaManager.isPause = isPause;
 }

 /**
  * release Release resources 
  */
 public static void release(){
  if(mMediaPlayer!=null){
   isPause = false;
   mMediaPlayer.stop();
   mMediaPlayer.release();
   mMediaPlayer = null;
  }
 }

 public synchronized static void reset(){
  if(mMediaPlayer!=null) {
   mMediaPlayer.reset();
   isPause = false;
  }
 }

 /**
  *  Judge whether the video is playing or not 
  * @return
  */
 public synchronized static boolean isPlaying(){

  return mMediaPlayer != null && mMediaPlayer.isPlaying();
 }
}

3. Sequential playback of voice lists


 private int lastPos = -1;
 // Play voice 
 private void playVoice(final int position, String from) {

  LogUtil.e("playVoice position",position+"");
  if(position >= records.size()) {
   LogUtil.e("playVoice"," It's all played ");
   stopAnimation();
   MediaManager.reset();
   return;
  }

  String voicePath = records.get(position).getPath();
  LogUtil.e("playVoice",voicePath);
  if(TextUtils.isEmpty(voicePath) || !voicePath.contains(".mp3")){
   Toast.makeText(this," Illegal voice file ",Toast.LENGTH_LONG).show();
   return;
  }

  if(lastPos != position && "itemClick".equals(from)){
   stopAnimation();
   MediaManager.reset();
  }
  lastPos = position;

// Get listview Certain 1 A picture control with entries 
  int pos = position - id_list_voice.getFirstVisiblePosition();
  View view = id_list_voice.getChildAt(pos);
  id_iv_voice = (ImageView) view.findViewById(R.id.id_iv_voice);
  LogUtil.e("playVoice position",pos+"");

  if(MediaManager.isPlaying()){
   MediaManager.pause();
   stopAnimation();
  }else if(MediaManager.isPause()){
   startAnimation();
   MediaManager.resume();
  }else{
   startAnimation();
   MediaManager.playSound(this,voicePath, new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
     // Stop animation after playing   Reset MediaManager
     stopAnimation();
     MediaManager.reset();

     playVoice(position + 1, "loop");
    }
   });
  }
 }

4. How to deal with the problem of single play and reuse of voice list

The playback logic is basically the same as above


private int lastPosition = -1;
 private void playVoice(FendaListInfo.ObjsEntity obj, int position) {
  String videoPath = obj.path;
  if(TextUtils.isEmpty(videoPath) || !videoPath.contains(".mp3")){
   Toast.makeText(this," Illegal voice file ",Toast.LENGTH_LONG).show();
   return;
  }
  if(position != lastPosition){ // Click on different items to stop animation first   Reset audio resources 
   stopAnimation();
   MediaManager.reset();
  }
  if(mAdapter!=null)
   mAdapter.selectItem(position, lastPosition);
  lastPosition = position;

  id_iv_voice.setBackgroundResource(R.drawable.animation_voice);
  animationDrawable = (AnimationDrawable) id_iv_voice.getBackground();
  if(MediaManager.isPlaying()){
   stopAnimation();
   MediaManager.pause();
  }else if(MediaManager.isPause()){
   startAnimation();
   MediaManager.resume();
  }else{
   startAnimation();
   MediaManager.playSound(this,videoPath, new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
     LogUtil.e("onCompletion"," Play complete ");
     stopAnimation();
     MediaManager.stop();
    }
   });
  }
 }

// Core method 
 // Clicked on a certain 1 Items   This entry isSelect=true  Upper 1 Items isSelect Need to read false  In the process of preventing sliding,   Frame animation reuse problem 
 public void selectItem(int position, int lastPosition) {

  LogUtil.e("selectItem"," ;lastPosition="+lastPosition+" ;position="+position);
  if(lastPosition >= 0 && lastPosition < mDatas.size() && lastPosition != position){
   FendaListInfo.ObjsEntity bean = mDatas.get(lastPosition);
   bean.isSelect = false;
   mDatas.set(lastPosition, bean);
   notifyDataSetChanged();
  }

  if(position < mDatas.size() && position != lastPosition){
   FendaListInfo.ObjsEntity bean = mDatas.get(position);
   bean.isSelect = true;
   mDatas.set(position,bean);
  }
 }
/**
 *  Animation processing of adapter picture playback 
 */
private void setVoiceAnimation(ImageView iv_voice, FendaListInfo.ObjsEntity obj) {

  // Dealing with the problem of animation reuse 
  AnimationDrawable animationDrawable;
  if(obj.isSelect){
   iv_voice.setBackgroundResource(R.drawable.animation_voice);
   animationDrawable = (AnimationDrawable) iv_voice.getBackground();
   if(MediaManager.isPlaying() && animationDrawable!=null){
    animationDrawable.start();
   }else{
    iv_voice.setBackgroundResource(R.drawable.voice_listen);
    animationDrawable.stop();
   }
  }else{
   iv_voice.setBackgroundResource(R.drawable.voice_listen);
  }
}

5. Download address

Realization of Voice Playing and Recording with Android


Related articles: