热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

Android用AudioRecord进行录音

这篇文章主要介绍了Android用AudioRecord进行录音的方法,帮助大家更好的理解和使用Android,感兴趣的朋友可以了解下

在音视频开发中,录音当然是必不可少的。首先我们要学会单独的录音功能,当然这里说的录音是指用AudioRecord来录音,读取录音原始数据,读到的就是所谓的PCM数据。对于录音来说,最重要的几个参数要搞明白:

1、simpleRate采样率,采样率就是采样频率,每秒钟记录多少个样本。

2、channelConfig通道配置,其实就是所谓的单通道,双通道之类的,AudioFormat.CHANNEL_IN_MONO单通道,AudioFormat.CHANNEL_IN_STEREO双通道,这里只列了这两种,还有其它的,可自行查阅。

3、audioFormat音频格式,其实就是采样的精度,每个样本的位数,AudioFormat.ENCODING_PCM_8BIT每个样本占8位,AudioFormat.ENCODING_PCM_16BIT每个样本占16位,这里也只用了这两个,别的没研究。

在学习过程中会用到的一些参数,我这里封装了一个类,如下

public class AudioParams {

  enum Format {
    SINGLE_8_BIT, DOUBLE_8_BIT, SINGLE_16_BIT, DOUBLE_16_BIT
  }

  private Format format;
  int simpleRate;

  AudioParams(int simpleRate, Format f) {
    this.simpleRate = simpleRate;
    this.format = f;
  }

  AudioParams(int simpleRate, int channelCount, int bits) {
    this.simpleRate = simpleRate;
    set(channelCount, bits);
  }

  int getBits() {
    return (format == Format.SINGLE_8_BIT || format == Format.DOUBLE_8_BIT) ? 8 : 16;
  }

  int getEncodingFormat() {
    return (format == Format.SINGLE_8_BIT || format == Format.DOUBLE_8_BIT) ? AudioFormat.ENCODING_PCM_8BIT :
      AudioFormat.ENCODING_PCM_16BIT;
  }

  int getChannelCount() {return (format == Format.SINGLE_8_BIT || format == Format.SINGLE_16_BIT) ? 1 : 2;}

  int getChannelConfig() {
    return (format == Format.SINGLE_8_BIT || format == Format.SINGLE_16_BIT) ? AudioFormat.CHANNEL_IN_MONO :
      AudioFormat.CHANNEL_IN_STEREO;
  }

  int getOutChannelConfig() {
    return (format == Format.SINGLE_8_BIT || format == Format.SINGLE_16_BIT) ? AudioFormat.CHANNEL_OUT_MONO :
      AudioFormat.CHANNEL_OUT_STEREO;
  }

  void set(int channelCount, int bits) {
    if ((channelCount != 1 && channelCount != 2) || (bits != 8 && bits != 16)) {
      throw new IllegalArgumentException("不支持其它格式 channelCount=$channelCount bits=$bits");
    }
    if (channelCount == 1) {
      if (bits == 8) {
        format = Format.SINGLE_8_BIT;
      } else {
        format = Format.SINGLE_16_BIT;
      }
    } else {
      if (bits == 8) {
        format = Format.DOUBLE_8_BIT;
      } else {
        format = Format.DOUBLE_16_BIT;
      }
    }
  }
}

这里固定使用了单通道8位,双通道8位,单通道16位,双通道16位,所以用了枚举来限制。

为了方便把录音数据拿出来显示、存储,这里写了一个回调方法如下

public interface RecordCallback {
    /**
     * 数据回调
     *
     * @param bytes 数据
     * @param len  数据有效长度,-1时表示数据结束
     */
    void onRecord(byte[] bytes, int len);
  }

有了这些参数,现在就可以录音了,先看一下样例

public void startRecord(AudioParams params, RecordCallback callback) {
    int simpleRate = params.simpleRate;
    int channelCOnfig= params.getChannelConfig();
    int audioFormat = params.getEncodingFormat();
    // 根据AudioRecord提供的api拿到最小缓存大小
    int bufferSize = AudioRecord.getMinBufferSize(simpleRate, channelConfig, audioFormat);
    //创建Record对象
    record = new AudioRecord(MediaRecorder.AudioSource.MIC, simpleRate, channelConfig, audioFormat, bufferSize);
    recordThread = new Thread(() -> {
      byte[] buffer = new byte[bufferSize];
      record.startRecording();
      recording = true;
      while (recording) {
        int read = record.read(buffer, 0, bufferSize);
        // 将数据回调到外部
        if (read > 0 && callback != null) {
          callback.onRecord(buffer, read);
        }
      }
      if (callback != null) {
        // len 为-1时表示结束
        callback.onRecord(buffer, -1);
        recording = false;
      }
      //释放资源
      release();
    });
    recordThread.start();
  }

这个方法就是简单的采集音频数据,这个数据就是最原始的pcm数据。

拿到pcm数据以后,如果直接保存到文件是无法直接播放的,因为这只是一堆数据,没有任何格式说明,如果想让普通播放器可以播放,需要在文件中加入文件头,来告诉播放器这个数据的格式,这里是直接保存成wav格式的数据。下面就是加入wav格式文件头的方法

private static byte[] getWaveFileHeader(int totalDataLen, int sampleRate, int channelCount, int bits) {
    byte[] header = new byte[44];
    // RIFF/WAVE header
    header[0] = 'R';
    header[1] = 'I';
    header[2] = 'F';
    header[3] = 'F';

    int fileLength = totalDataLen + 36;
    header[4] = (byte) (fileLength & 0xff);
    header[5] = (byte) (fileLength >> 8 & 0xff);
    header[6] = (byte) (fileLength >> 16 & 0xff);
    header[7] = (byte) (fileLength >> 24 & 0xff);
    //WAVE
    header[8] = 'W';
    header[9] = 'A';
    header[10] = 'V';
    header[11] = 'E';
    // 'fmt ' chunk
    header[12] = 'f';
    header[13] = 'm';
    header[14] = 't';
    header[15] = ' ';
    // 4 bytes: size of 'fmt ' chunk
    header[16] = 16;
    header[17] = 0;
    header[18] = 0;
    header[19] = 0;

    // pcm format = 1
    header[20] = 1;
    header[21] = 0;
    header[22] = (byte) channelCount;
    header[23] = 0;

    header[24] = (byte) (sampleRate & 0xff);
    header[25] = (byte) (sampleRate >> 8 & 0xff);
    header[26] = (byte) (sampleRate >> 16 & 0xff);
    header[27] = (byte) (sampleRate >> 24 & 0xff);

    int byteRate = sampleRate * bits * channelCount / 8;
    header[28] = (byte) (byteRate & 0xff);
    header[29] = (byte) (byteRate >> 8 & 0xff);
    header[30] = (byte) (byteRate >> 16 & 0xff);
    header[31] = (byte) (byteRate >> 24 & 0xff);
    // block align
    header[32] = (byte) (channelCount * bits / 8);
    header[33] = 0;
    // bits per sample
    header[34] = (byte) bits;
    header[35] = 0;
    //data
    header[36] = 'd';
    header[37] = 'a';
    header[38] = 't';
    header[39] = 'a';
    header[40] = (byte) (totalDataLen & 0xff);
    header[41] = (byte) (totalDataLen >> 8 & 0xff);
    header[42] = (byte) (totalDataLen >> 16 & 0xff);
    header[43] = (byte) (totalDataLen >> 24 & 0xff);
    return header;
  }

根据几个参数设置一下文件头,然后直接写入录音采集到的pcm数据,就可被正常播放了。wav文件头格式定义,可点击这里查看或自行百度。

如果想要通过AudioRecord录音直接保存到文件,可参考下面方法

public void startRecord(String filePath, AudioParams params, RecordCallback callback) {
    int channelCount = params.getChannelCount();
    int bits = params.getBits();

    final boolean storeFile = filePath != null && !filePath.isEmpty();

    startRecord(params, (bytes, len) -> {
      if (storeFile) {
        if (file == null) {
          File f = new File(filePath);
          if (f.exists()) {
            f.delete();
          }
          try {
            file = new RandomAccessFile(f, "rw");
            file.write(getWaveFileHeader(0, params.simpleRate, channelCount, bits));
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (len > 0) {
          try {
            file.write(bytes, 0, len);
          } catch (IOException e) {
            e.printStackTrace();
          }
        } else {
          try {
            // 因为在前面已经写入头信息,所以这里要减去头信息才是数据的长度
            int length = (int) file.length() - 44;
            file.seek(0);
            file.write(getWaveFileHeader(length, params.simpleRate, channelCount, bits));
            file.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
      if (callback != null) {
        callback.onRecord(bytes, len);
      }
    });
  }

先通过RandomAccessFile创建文件,先写入文件头,由于暂时我们不知道会录多长,有多少pcm数据,长度先用0表示,等录音结束后,通过seek(int)方法重新写入文件头信息,也可以先把pcm数据保存到临时文件,然后再写入到一个新的文件中,这里就不举例说明了。

最后放入完整类的代码

package cn.sskbskdrin.record.audio;

import android.media.AudioRecord;
import android.media.MediaRecorder;

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

/**
 * @author sskbskdrin
 * @date 2019/April/3
 */
public class AudioRecordManager {

  private AudioParams DEFAULT_FORMAT = new AudioParams(8000, 1, 16);

  private AudioRecord record;

  private Thread recordThread;

  private boolean recording = false;

  private RandomAccessFile file;

  public void startRecord(String filePath, RecordCallback callback) {
    startRecord(filePath, DEFAULT_FORMAT, callback);
  }

  public void startRecord(String filePath, AudioParams params, RecordCallback callback) {
    int channelCount = params.getChannelCount();
    int bits = params.getBits();

    final boolean storeFile = filePath != null && !filePath.isEmpty();

    startRecord(params, (bytes, len) -> {
      if (storeFile) {
        if (file == null) {
          File f = new File(filePath);
          if (f.exists()) {
            f.delete();
          }
          try {
            file = new RandomAccessFile(f, "rw");
            file.write(getWaveFileHeader(0, params.simpleRate, channelCount, bits));
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (len > 0) {
          try {
            file.write(bytes, 0, len);
          } catch (IOException e) {
            e.printStackTrace();
          }
        } else {
          try {
            // 因为在前面已经写入头信息,所以这里要减去头信息才是数据的长度
            int length = (int) file.length() - 44;
            file.seek(0);
            file.write(getWaveFileHeader(length, params.simpleRate, channelCount, bits));
            file.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
      if (callback != null) {
        callback.onRecord(bytes, len);
      }
    });
  }

  public void startRecord(AudioParams params, RecordCallback callback) {
    int simpleRate = params.simpleRate;
    int channelCOnfig= params.getChannelConfig();
    int audioFormat = params.getEncodingFormat();
    // 根据AudioRecord提供的api拿到最小缓存大小
    int bufferSize = AudioRecord.getMinBufferSize(simpleRate, channelConfig, audioFormat);
    //创建Record对象
    record = new AudioRecord(MediaRecorder.AudioSource.MIC, simpleRate, channelConfig, audioFormat, bufferSize);
    recordThread = new Thread(() -> {
      byte[] buffer = new byte[bufferSize];
      record.startRecording();
      recording = true;
      while (recording) {
        int read = record.read(buffer, 0, bufferSize);
        // 将数据回调到外部
        if (read > 0 && callback != null) {
          callback.onRecord(buffer, read);
        }
      }
      if (callback != null) {
        // len 为-1时表示结束
        callback.onRecord(buffer, -1);
        recording = false;
      }
      //释放资源
      release();
    });
    recordThread.start();
  }

  public void stop() {
    recording = false;
  }

  public void release() {
    recording = false;
    if (record != null) {
      record.stop();
      record.release();
    }
    record = null;
    file = null;
    recordThread = null;
  }

  private static byte[] getWaveFileHeader(int totalDataLen, int sampleRate, int channelCount, int bits) {
    byte[] header = new byte[44];
    // RIFF/WAVE header
    header[0] = 'R';
    header[1] = 'I';
    header[2] = 'F';
    header[3] = 'F';

    int fileLength = totalDataLen + 36;
    header[4] = (byte) (fileLength & 0xff);
    header[5] = (byte) (fileLength >> 8 & 0xff);
    header[6] = (byte) (fileLength >> 16 & 0xff);
    header[7] = (byte) (fileLength >> 24 & 0xff);
    //WAVE
    header[8] = 'W';
    header[9] = 'A';
    header[10] = 'V';
    header[11] = 'E';
    // 'fmt ' chunk
    header[12] = 'f';
    header[13] = 'm';
    header[14] = 't';
    header[15] = ' ';
    // 4 bytes: size of 'fmt ' chunk
    header[16] = 16;
    header[17] = 0;
    header[18] = 0;
    header[19] = 0;

    // pcm format = 1
    header[20] = 1;
    header[21] = 0;
    header[22] = (byte) channelCount;
    header[23] = 0;

    header[24] = (byte) (sampleRate & 0xff);
    header[25] = (byte) (sampleRate >> 8 & 0xff);
    header[26] = (byte) (sampleRate >> 16 & 0xff);
    header[27] = (byte) (sampleRate >> 24 & 0xff);

    int byteRate = sampleRate * bits * channelCount / 8;
    header[28] = (byte) (byteRate & 0xff);
    header[29] = (byte) (byteRate >> 8 & 0xff);
    header[30] = (byte) (byteRate >> 16 & 0xff);
    header[31] = (byte) (byteRate >> 24 & 0xff);
    // block align
    header[32] = (byte) (channelCount * bits / 8);
    header[33] = 0;
    // bits per sample
    header[34] = (byte) bits;
    header[35] = 0;
    //data
    header[36] = 'd';
    header[37] = 'a';
    header[38] = 't';
    header[39] = 'a';
    header[40] = (byte) (totalDataLen & 0xff);
    header[41] = (byte) (totalDataLen >> 8 & 0xff);
    header[42] = (byte) (totalDataLen >> 16 & 0xff);
    header[43] = (byte) (totalDataLen >> 24 & 0xff);
    return header;
  }

  public interface RecordCallback {
    /**
     * 数据回调
     *
     * @param bytes 数据
     * @param len  数据有效长度,-1时表示数据结束
     */
    void onRecord(byte[] bytes, int len);
  }
}

如有不对之处还请评论指正

以上就是Android用AudioRecord进行录音的详细内容,更多关于Android AudioRecord的资料请关注其它相关文章!


推荐阅读
  • 本文介绍了如何使用PHP向系统日历中添加事件的方法,通过使用PHP技术可以实现自动添加事件的功能,从而实现全局通知系统和迅速记录工具的自动化。同时还提到了系统exchange自带的日历具有同步感的特点,以及使用web技术实现自动添加事件的优势。 ... [详细]
  • Monkey《大话移动——Android与iOS应用测试指南》的预购信息发布啦!
    Monkey《大话移动——Android与iOS应用测试指南》的预购信息已经发布,可以在京东和当当网进行预购。感谢几位大牛给出的书评,并呼吁大家的支持。明天京东的链接也将发布。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • Android Studio Bumblebee | 2021.1.1(大黄蜂版本使用介绍)
    本文介绍了Android Studio Bumblebee | 2021.1.1(大黄蜂版本)的使用方法和相关知识,包括Gradle的介绍、设备管理器的配置、无线调试、新版本问题等内容。同时还提供了更新版本的下载地址和启动页面截图。 ... [详细]
  • 本文讲述了作者通过点火测试男友的性格和承受能力,以考验婚姻问题。作者故意不安慰男友并再次点火,观察他的反应。这个行为是善意的玩人,旨在了解男友的性格和避免婚姻问题。 ... [详细]
  • 安卓select模态框样式改变_微软Office风格的多端(Web、安卓、iOS)组件库——Fabric UI...
    介绍FabricUI是微软开源的一套Office风格的多端组件库,共有三套针对性的组件,分别适用于web、android以及iOS,Fab ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 解决Cydia数据库错误:could not open file /var/lib/dpkg/status 的方法
    本文介绍了解决iOS系统中Cydia数据库错误的方法。通过使用苹果电脑上的Impactor工具和NewTerm软件,以及ifunbox工具和终端命令,可以解决该问题。具体步骤包括下载所需工具、连接手机到电脑、安装NewTerm、下载ifunbox并注册Dropbox账号、下载并解压lib.zip文件、将lib文件夹拖入Books文件夹中,并将lib文件夹拷贝到/var/目录下。以上方法适用于已经越狱且出现Cydia数据库错误的iPhone手机。 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 本文由编程笔记#小编整理,主要介绍了关于数论相关的知识,包括数论的算法和百度百科的链接。文章还介绍了欧几里得算法、辗转相除法、gcd、lcm和扩展欧几里得算法的使用方法。此外,文章还提到了数论在求解不定方程、模线性方程和乘法逆元方面的应用。摘要长度:184字。 ... [详细]
author-avatar
优优绿园之时尚饰品_834
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有