溫馨提示×

溫馨提示×

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

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

利用libmp3lame實(shí)現(xiàn)在Android上錄音MP3文件示例

發(fā)布時間:2020-10-01 21:09:11 來源:腳本之家 閱讀:248 作者:clam314 欄目:移動開發(fā)

之前項(xiàng)目需要實(shí)現(xiàn)MP3的錄音,于是使用上了Lame這個庫。這次做一個demo,使用AndroidStudio+Cmake+NDK進(jìn)行開發(fā)。利用Android SDK提供的AndroidRecorder進(jìn)行錄音,得到PCM數(shù)據(jù),并使用jni調(diào)用Lame這個C庫將PCM數(shù)據(jù)轉(zhuǎn)換為MP3文件。并使用MediaPlayer對錄音的MP3文件進(jìn)行播放。另外此次的按鍵是仿微信的語音按鍵,按下錄音,松開結(jié)束,若中途上滑松開即取消

效果如下:

利用libmp3lame實(shí)現(xiàn)在Android上錄音MP3文件示例

項(xiàng)目地址: LameMp3ForAndroid_jb51.rar

一、主要類的介紹

  • Mp3Recorder—— 是負(fù)責(zé)調(diào)用AudioRecorder進(jìn)行錄音的類
  • SimpleLame——是負(fù)責(zé)將MP3Recorder錄制出的PCM數(shù)據(jù)轉(zhuǎn)換成MP3文件
  • DataEncodeThread——是負(fù)責(zé)執(zhí)行PCM轉(zhuǎn)MP3的線程
  • LameMp3Manager——是對Mp3Recorder的多一次封裝,增加了取消后刪除之前錄制的數(shù)據(jù)的邏輯
  • MediaPlayerUtil——是對系統(tǒng)的MediaPlayer進(jìn)行簡單的封裝,使其只需要三步就可以播放音頻文件
  • MediaRecorderButton ——是一個仿微信錄音按鍵的控件,按下錄制,松開結(jié)束,錄制時上滑則取消錄制

二、錄制的流程

  1. Mp3Recorder調(diào)用startRecording()開始錄制并初始化DataEncoderThread線程,并定期將錄制的PCM數(shù)據(jù),傳入DataEncoderThread中。
  2. 在DataEncoderThread里,SimpleLame將Mp3Recorder傳入的PCM數(shù)據(jù)轉(zhuǎn)換成MP3格式并寫入文件,其中SimpleLame通過jni對Lame庫進(jìn)行調(diào)用
  3. Mp3Recorder調(diào)用stopRecording()停止錄制,并通知DataEncoderThread線程錄制結(jié)束,DataEncoderThread將剩余的數(shù)據(jù)轉(zhuǎn)換完畢。

三、主要的實(shí)現(xiàn)代碼

Mp3Recorder

public class Mp3Recorder {
  static {
    System.loadLibrary("lamemp3");
  }
  //默認(rèn)采樣率
  private static final int DEFAULT_SAMPLING_RATE = 44100;
  //轉(zhuǎn)換周期,錄音每滿160幀,進(jìn)行一次轉(zhuǎn)換
  private static final int FRAME_COUNT = 160;
  //輸出MP3的碼率
  private static final int BIT_RATE = 32;
  //根據(jù)資料假定的最大值。 實(shí)測時有時超過此值。
  private static final int MAX_VOLUME = 2000;
  private AudioRecord audioRecord = null;
  private int bufferSize;
  private File mp3File;
  private int mVolume;
  private short[] mPCMBuffer;
  private FileOutputStream os = null;
  private DataEncodeThread encodeThread;
  private int samplingRate;
  private int channelConfig;
  private PCMFormat audioFormat;
  private boolean isRecording = false;
  private ExecutorService executor = Executors.newFixedThreadPool(1);
  private OnFinishListener finishListener;

  public interface OnFinishListener {
    void onFinish(String mp3SavePath);
  }

  public Mp3Recorder(int samplingRate, int channelConfig, PCMFormat audioFormat) {
    this.samplingRate = samplingRate;
    this.channelConfig = channelConfig;
    this.audioFormat = audioFormat;
  }

  public Mp3Recorder() {
    this(DEFAULT_SAMPLING_RATE, AudioFormat.CHANNEL_IN_MONO, PCMFormat.PCM_16BIT);
  }


  public void startRecording(File mp3Save) throws IOException {
    if (isRecording) return;
    this.mp3File = mp3Save;
    if (audioRecord == null) {
      initAudioRecorder();
    }
    audioRecord.startRecording();
    Runnable runnable = new Runnable() {
      @Override
      public void run() {
        isRecording = true;
        //循環(huán)的從AudioRecord獲取錄音的PCM數(shù)據(jù)
        while (isRecording) {
          int readSize = audioRecord.read(mPCMBuffer, 0, bufferSize);
          if (readSize > 0) {
            //待轉(zhuǎn)換的PCM數(shù)據(jù)放到轉(zhuǎn)換線程中
            encodeThread.addChangeBuffer(mPCMBuffer,readSize);
            calculateRealVolume(mPCMBuffer, readSize);
          }
        }
        // 錄音完畢,釋放AudioRecord的資源
        try {
          audioRecord.stop();
          audioRecord.release();
          audioRecord = null;
          // 錄音完畢,通知轉(zhuǎn)換線程停止,并等待直到其轉(zhuǎn)換完畢
          Message msg = Message.obtain(encodeThread.getHandler(), DataEncodeThread.PROCESS_STOP);
          msg.sendToTarget();
          encodeThread.join();
          //轉(zhuǎn)換完畢后回調(diào)監(jiān)聽
          if(finishListener != null) finishListener.onFinish(mp3File.getPath());
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
          if (os != null) {
            try {
              os.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
    };
    executor.execute(runnable);
  }

  public void stopRecording() throws IOException {
    isRecording = false;
  }

  //計(jì)算音量大小
  private void calculateRealVolume(short[] buffer, int readSize) {
    double sum = 0;
    for (int i = 0; i < readSize; i++) {
      sum += buffer[i] * buffer[i];
    }
    if (readSize > 0) {
      double amplitude = sum / readSize;
      mVolume = (int) Math.sqrt(amplitude);
    }
  }

  public int getVolume(){
    if (mVolume >= MAX_VOLUME) {
      return MAX_VOLUME;
    }
    return mVolume;
  }

  public int getMaxVolume(){
    return MAX_VOLUME;
  }

  public void setFinishListener(OnFinishListener listener){
    this.finishListener = listener;
  }

  private void initAudioRecorder() throws IOException {
    int bytesPerFrame = audioFormat.getBytesPerFrame();
    //計(jì)算緩沖區(qū)的大小,使其是設(shè)置周期幀數(shù)的整數(shù)倍,方便循環(huán)
    int frameSize = AudioRecord.getMinBufferSize(samplingRate, channelConfig, audioFormat.getAudioFormat()) / bytesPerFrame;
    if (frameSize % FRAME_COUNT != 0) {
      frameSize = frameSize + (FRAME_COUNT - frameSize % FRAME_COUNT);
    }
    bufferSize = frameSize * bytesPerFrame;

    audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, samplingRate, channelConfig, audioFormat.getAudioFormat(), bufferSize);
    mPCMBuffer = new short[bufferSize];
    SimpleLame.init(samplingRate, 1, samplingRate, BIT_RATE);
    os = new FileOutputStream(mp3File);
    // 創(chuàng)建轉(zhuǎn)碼的線程
    encodeThread = new DataEncodeThread(os, bufferSize);
    encodeThread.start();
    //給AudioRecord設(shè)置刷新監(jiān)聽,待錄音幀數(shù)每次達(dá)到FRAME_COUNT,就通知轉(zhuǎn)換線程轉(zhuǎn)換一次數(shù)據(jù)
    audioRecord.setRecordPositionUpdateListener(encodeThread, encodeThread.getHandler());
    audioRecord.setPositionNotificationPeriod(FRAME_COUNT);
  }
}

DataEncodeThread

public class DataEncodeThread extends Thread implements AudioRecord.OnRecordPositionUpdateListener {

  public static final int PROCESS_STOP = 1;
  private StopHandler handler;
  private byte[] mp3Buffer;
  //用于存取待轉(zhuǎn)換的PCM數(shù)據(jù)
  private List<ChangeBuffer> mChangeBuffers = Collections.synchronizedList(new LinkedList<ChangeBuffer>());
  private FileOutputStream os;
  private CountDownLatch handlerInitLatch = new CountDownLatch(1);

  private static class StopHandler extends Handler {
    WeakReference<DataEncodeThread> encodeThread;

    public StopHandler(DataEncodeThread encodeThread) {
      this.encodeThread = new WeakReference<>(encodeThread);
    }

    @Override
    public void handleMessage(Message msg) {
      if (msg.what == PROCESS_STOP) {
        DataEncodeThread threadRef = encodeThread.get();
        //錄音停止后,將剩余的PCM數(shù)據(jù)轉(zhuǎn)換完畢
        for (;threadRef.processData() > 0;);
        removeCallbacksAndMessages(null);
        threadRef.flushAndRelease();
        getLooper().quit();
      }
      super.handleMessage(msg);
    }
  }

  public DataEncodeThread(FileOutputStream os, int bufferSize) {
    this.os = os;
    mp3Buffer = new byte[(int) (7200 + (bufferSize * 2 * 1.25))];
  }

  @Override
  public void run() {
    Looper.prepare();
    handler = new StopHandler(this);
    handlerInitLatch.countDown();
    Looper.loop();
  }

  public Handler getHandler() {
    try {
      handlerInitLatch.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
      Log.e(TAG, "Error when waiting handle to init");
    }
    return handler;
  }

  @Override
  public void onMarkerReached(AudioRecord recorder) {
    // Do nothing
  }

  @Override
  public void onPeriodicNotification(AudioRecord recorder) {
    //由AudioRecord進(jìn)行回調(diào),滿足幀數(shù),通知數(shù)據(jù)轉(zhuǎn)換
    processData();
  }

  //從緩存區(qū)ChangeBuffers里獲取待轉(zhuǎn)換的PCM數(shù)據(jù),轉(zhuǎn)換為MP3數(shù)據(jù),并寫入文件
  private int processData() {
    if(mChangeBuffers != null && mChangeBuffers.size() > 0) {
      ChangeBuffer changeBuffer = mChangeBuffers.remove(0);
      short[] buffer = changeBuffer.getData();
      int readSize = changeBuffer.getReadSize();
      Log.d(TAG, "Read size: " + readSize);
      if (readSize > 0) {
        int encodedSize = SimpleLame.encode(buffer, buffer, readSize, mp3Buffer);
        if (encodedSize < 0) {
          Log.e(TAG, "Lame encoded size: " + encodedSize);
        }
        try {
          os.write(mp3Buffer, 0, encodedSize);
        } catch (IOException e) {
          e.printStackTrace();
          Log.e(TAG, "Unable to write to file");
        }
        return readSize;
      }
    }
    return 0;
  }

  private void flushAndRelease() {
    final int flushResult = SimpleLame.flush(mp3Buffer);

    if (flushResult > 0) {
      try {
        os.write(mp3Buffer, 0, flushResult);
      } catch (final IOException e) {
        e.printStackTrace();
      }
    }
  }

  public void addChangeBuffer(short[] rawData, int readSize){
    mChangeBuffers.add(new ChangeBuffer(rawData, readSize));
  }

  private class ChangeBuffer{
    private short[] rawData;
    private int readSize;
    public ChangeBuffer(short[] rawData, int readSize){
      this.rawData = rawData.clone();
      this.readSize = readSize;
    }
    public short[] getData(){
      return rawData;
    }
    public int getReadSize(){
      return readSize;
    }
  }
}

SimpleLame 主要的邏輯是通過jni調(diào)用Lame庫

public class SimpleLame {

  public native static void close();

  public native static int encode(short[] buffer_l, short[] buffer_r, int samples, byte[] mp3buf);

  public native static int flush(byte[] mp3buf);

  public native static void init(int inSampleRate, int outChannel, int outSampleRate, int outBitrate, int quality);

  public static void init(int inSampleRate, int outChannel, int outSampleRate, int outBitrate) {
    init(inSampleRate, outChannel, outSampleRate, outBitrate, 7);
  }
}

#include <cwchar>
#include "SimpleLame.h"
#include "lamemp3/lame.h"

static lame_global_flags *glf = NULL;

void Java_com_clam314_lame_SimpleLame_close(JNIEnv *env, jclass type){
  lame_close(glf);
  glf = NULL;
}

jint Java_com_clam314_lame_SimpleLame_encode(JNIEnv *env, jclass type, jshortArray buffer_l_,
                    jshortArray buffer_r_, jint samples, jbyteArray mp3buf_) {
  jshort *buffer_l = env->GetShortArrayElements(buffer_l_, NULL);
  jshort *buffer_r = env->GetShortArrayElements(buffer_r_, NULL);
  jbyte *mp3buf = env->GetByteArrayElements(mp3buf_, NULL);

  const jsize mp3buf_size = env->GetArrayLength(mp3buf_);

  int result =lame_encode_buffer(glf, buffer_l, buffer_r, samples, (u_char*)mp3buf, mp3buf_size);

  env->ReleaseShortArrayElements(buffer_l_, buffer_l, 0);
  env->ReleaseShortArrayElements(buffer_r_, buffer_r, 0);
  env->ReleaseByteArrayElements(mp3buf_, mp3buf, 0);

  return result;
}

jint Java_com_clam314_lame_SimpleLame_flush(JNIEnv *env, jclass type, jbyteArray mp3buf_) {
  jbyte *mp3buf = env->GetByteArrayElements(mp3buf_, NULL);

  const jsize mp3buf_size = env->GetArrayLength(mp3buf_);

  int result = lame_encode_flush(glf, (u_char*)mp3buf, mp3buf_size);

  env->ReleaseByteArrayElements(mp3buf_, mp3buf, 0);

  return result;
}

void Java_com_clam314_lame_SimpleLame_init__IIIII(JNIEnv *env, jclass type, jint inSampleRate, jint outChannel,
                       jint outSampleRate, jint outBitrate, jint quality) {
  if(glf != NULL){
    lame_close(glf);
    glf = NULL;
  }
  glf = lame_init();
  lame_set_in_samplerate(glf, inSampleRate);
  lame_set_num_channels(glf, outChannel);
  lame_set_out_samplerate(glf, outSampleRate);
  lame_set_brate(glf, outBitrate);
  lame_set_quality(glf, quality);
  lame_init_params(glf);
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

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

AI