溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android如何實現(xiàn)語音播放與錄音功能

發(fā)布時間:2021-04-17 09:50:05 來源:億速云 閱讀:257 作者:小新 欄目:移動開發(fā)

這篇文章主要介紹Android如何實現(xiàn)語音播放與錄音功能,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

具體內容如下

項目用到的技術點和亮點

  • 語音錄音 (單個和列表)

  • 語音播放(單個和列表)

  • 語音錄音封裝

  • 語音播放器封裝

  • 語音列表順序播放

  • 語音列表單個播放 復用問題處理

因為安裝原生錄音不能錄mp3格式文件 而mp3格式是安卓和ios公用的,所以我們需要的是能直接錄取mp3文件或者錄完的格式轉成mp3格式

下面添加這個庫 能直接錄mp3文件,我覺得是最方便的

compile ‘com.czt.mp3recorder:library:1.0.3'

1. 語音錄音封裝

代碼簡單 自己看吧

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;       // 文件夾的名稱
  private String mCurrentFilePath;
  private static AudioManage mInstance;

  private boolean isPrepared; // 標識MediaRecorder準備完畢
  private AudioManage(String dir) {
    mDir = dir;
    LogUtil.e("AudioManage=",mDir);
  }

  /**
   * 回調“準備完畢”
   * @author zlc
   */
  public interface AudioStateListenter {
    void wellPrepared();  // prepared完畢
  }

  public AudioStateListenter mListenter;

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

  /**
   * 使用單例實現(xiàn) AudioManage
   * @param dir
   * @return
   */
  public static AudioManage getInstance(String dir) {
    if (mInstance == null) {
      synchronized (AudioManage.class) {  // 同步
        if (mInstance == null) {
          mInstance = new AudioManage(dir);
        }
      }
    }
    return mInstance;
  }

  /**
   * 準備錄音
   */
  public void prepareAudio() {

    try {
      isPrepared = false;
      File dir = new File(mDir);
      if (!dir.exists()) {
        dir.mkdirs();
      }
      String fileName = GenerateFileName(); // 文件名字
      File file = new File(dir, fileName); // 路徑+文件名字
      //MediaRecorder可以實現(xiàn)錄音和錄像。需要嚴格遵守API說明中的函數(shù)調用先后順序.
      mRecorder = new MP3Recorder(file);
      mCurrentFilePath = file.getAbsolutePath();
//     mMediaRecorder = new MediaRecorder();
//     mCurrentFilePath = file.getAbsolutePath();
//     mMediaRecorder.setOutputFile(file.getAbsolutePath());  // 設置輸出文件
//     mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);  // 設置MediaRecorder的音頻源為麥克風
//     mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);  // 設置音頻的格式
//     mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);  // 設置音頻的編碼為AMR_NB
//     mMediaRecorder.prepare();
//     mMediaRecorder.start();
      mRecorder.start();  //開始錄音
      isPrepared = true; // 準備結束
      if (mListenter != null) {
        mListenter.wellPrepared();
      }
    } catch (Exception e) {
      e.printStackTrace();
      LogUtil.e("prepareAudio",e.getMessage());
    }

  }

  /**
   * 隨機生成文件名稱
   * @return
   */
  private String GenerateFileName() {
    // TODO Auto-generated method stub
    return UUID.randomUUID().toString() + ".mp3"; // 音頻文件格式
  }


  /**
   * 獲得音量等級——通過mMediaRecorder獲得振幅,然后換算成聲音Level
   * maxLevel最大為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;
  }

  /**
   * 釋放資源
   */
  public void release() {
    if(mRecorder != null) {
      mRecorder.stop();
      mRecorder = null;
    }
  }

  /**
   * 停止錄音
   */
  public void stop(){
    if(mRecorder!=null && mRecorder.isRecording()){
      mRecorder.stop();
    }
  }

  /**
   * 取消(釋放資源+刪除文件)
   */
  public void delete() {
    release();
    if (mCurrentFilePath != null) {
      File file = new File(mCurrentFilePath);
      file.delete();  //刪除錄音文件
      mCurrentFilePath = null;
    }
  }

  public String getCurrentFilePath() {
    return mCurrentFilePath;
  }

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

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

2. 語音播放器封裝

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;  //播放錄音文件
  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;
        }
      });
    }
  }


  /**
   * 播放音頻
   * @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 {
      //詳見“MediaPlayer”調用過程圖
      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("語音error==",e.getMessage());
    }
  }


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

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

  /**
   * resume繼續(xù)
   */
  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釋放資源
   */
  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;
    }
  }

  /**
   * 判斷是否在播放視頻
   * @return
   */
  public synchronized static boolean isPlaying(){

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

3. 語音列表順序播放

 private int lastPos = -1;
  //播放語音
 private void playVoice(final int position, String from) {

    LogUtil.e("playVoice position",position+"");
    if(position >= records.size()) {
      LogUtil.e("playVoice","全部播放完了");
      stopAnimation();
      MediaManager.reset();
      return;
    }

    String voicePath = records.get(position).getPath();
    LogUtil.e("playVoice",voicePath);
    if(TextUtils.isEmpty(voicePath) || !voicePath.contains(".mp3")){
      Toast.makeText(this,"語音文件不合法",Toast.LENGTH_LONG).show();
      return;
    }

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

//獲取listview某一個條目的圖片控件
    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) {
          //播放完停止動畫 重置MediaManager
          stopAnimation();
          MediaManager.reset();

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

4. 語音列表單個播放 復用問題處理

播放邏輯基本同上

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,"語音文件不合法",Toast.LENGTH_LONG).show();
      return;
    }
    if(position != lastPosition){ //點擊不同條目先停止動畫 重置音頻資源
      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","播放完成");
          stopAnimation();
          MediaManager.stop();
        }
      });
    }
  }

//核心方法
 //點擊了某一個條目 這個條目isSelect=true 上一個條目isSelect需要改為false 防止滑動過程中 幀動畫復用問題
  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);
    }
  }
/**
 * 適配器圖片播放的動畫處理
 */
private void setVoiceAnimation(ImageView iv_voice, FendaListInfo.ObjsEntity obj) {

    //處理動畫復用問題
    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);
    }
  }

以上是“Android如何實現(xiàn)語音播放與錄音功能”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI