使用AudioCapturer开发音频录制功能

2024-02-16 13:55 更新

AudioCapturer是音频采集器,用于录制PCM(Pulse Code Modulation)音频数据,适合有音频开发经验的开发者实现更灵活的录制功能。

开发指导

使用AudioCapturer录制音频涉及到AudioCapturer实例的创建、音频采集参数的配置、采集的开始与停止、资源的释放等。本开发指导将以一次录制音频数据的过程为例,向开发者讲解如何使用AudioCapturer进行音频录制,建议搭配AudioCapturer的API说明阅读。

下图展示了AudioCapturer的状态变化,在创建实例后,调用对应的方法可以进入指定的状态实现对应的行为。需要注意的是在确定的状态执行不合适的方法可能导致AudioCapturer发生错误,建议开发者在调用状态转换的方法前进行状态检查,避免程序运行产生预期以外的结果。

图1 AudioCapturer状态变化示意图

使用on('stateChange')方法可以监听AudioCapturer的状态变化,每个状态对应值与说明见AudioState

开发步骤及注意事项

  1. 配置音频采集参数并创建AudioCapturer实例,音频采集参数的详细信息可以查看AudioCapturerOptions
    1. import audio from '@ohos.multimedia.audio';
    2. let audioStreamInfo = {
    3. samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
    4. channels: audio.AudioChannel.CHANNEL_2,
    5. sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
    6. encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
    7. };
    8. let audioCapturerInfo = {
    9. source: audio.SourceType.SOURCE_TYPE_MIC,
    10. capturerFlags: 0
    11. };
    12. let audioCapturerOptions = {
    13. streamInfo: audioStreamInfo,
    14. capturerInfo: audioCapturerInfo
    15. };
    16. audio.createAudioCapturer(audioCapturerOptions, (err, data) => {
    17. if (err) {
    18. console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`);
    19. } else {
    20. console.info('Invoke createAudioCapturer succeeded.');
    21. let audioCapturer = data;
    22. }
    23. });
  2. 调用start()方法进入running状态,开始录制音频。
    1. audioCapturer.start((err) => {
    2. if (err) {
    3. console.error(`Capturer start failed, code is ${err.code}, message is ${err.message}`);
    4. } else {
    5. console.info('Capturer start success.');
    6. }
    7. });
  3. 指定录制文件地址,调用read()方法读取缓冲区的数据。
    1. let file = fs.openSync(path, 0o2 | 0o100);
    2. let bufferSize = await audioCapturer.getBufferSize();
    3. let buffer = await audioCapturer.read(bufferSize, true);
    4. fs.writeSync(file.fd, buffer);
  4. 调用stop()方法停止录制。
    1. audioCapturer.stop((err) => {
    2. if (err) {
    3. console.error(`Capturer stop failed, code is ${err.code}, message is ${err.message}`);
    4. } else {
    5. console.info('Capturer stopped.');
    6. }
    7. });
  5. 调用release()方法销毁实例,释放资源。
    1. audioCapturer.release((err) => {
    2. if (err) {
    3. console.error(`capturer release failed, code is ${err.code}, message is ${err.message}`);
    4. } else {
    5. console.info('capturer released.');
    6. }
    7. });

完整示例

下面展示了使用AudioCapturer录制音频的完整示例代码。
  1. import audio from '@ohos.multimedia.audio';
  2. import fs from '@ohos.file.fs';
  3. const TAG = 'AudioCapturerDemo';
  4. export default class AudioCapturerDemo {
  5. private audioCapturer = undefined;
  6. private audioStreamInfo = {
  7. samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
  8. channels: audio.AudioChannel.CHANNEL_1,
  9. sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
  10. encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
  11. }
  12. private audioCapturerInfo = {
  13. source: audio.SourceType.SOURCE_TYPE_MIC, // 音源类型
  14. capturerFlags: 0 // 音频采集器标志
  15. }
  16. private audioCapturerOptions = {
  17. streamInfo: this.audioStreamInfo,
  18. capturerInfo: this.audioCapturerInfo
  19. }
  20. // 初始化,创建实例,设置监听事件
  21. init() {
  22. audio.createAudioCapturer(this.audioCapturerOptions, (err, capturer) => { // 创建AudioCapturer实例
  23. if (err) {
  24. console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`);
  25. return;
  26. }
  27. console.info(`${TAG}: create AudioCapturer success`);
  28. this.audioCapturer = capturer;
  29. this.audioCapturer.on('markReach', 1000, (position) => { // 订阅markReach事件,当采集的帧数达到1000时触发回调
  30. if (position === 1000) {
  31. console.info('ON Triggered successfully');
  32. }
  33. });
  34. this.audioCapturer.on('periodReach', 2000, (position) => { // 订阅periodReach事件,当采集的帧数达到2000时触发回调
  35. if (position === 2000) {
  36. console.info('ON Triggered successfully');
  37. }
  38. });
  39. });
  40. }
  41. // 开始一次音频采集
  42. async start() {
  43. let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED];
  44. if (stateGroup.indexOf(this.audioCapturer.state) === -1) { // 当且仅当状态为STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一时才能启动采集
  45. console.error(`${TAG}: start failed`);
  46. return;
  47. }
  48. await this.audioCapturer.start(); // 启动采集
  49. let context = getContext(this);
  50. const path = context.filesDir + '/test.wav'; // 采集到的音频文件存储路径
  51. let file = fs.openSync(path, 0o2 | 0o100); // 如果文件不存在则创建文件
  52. let fd = file.fd;
  53. let numBuffersToCapture = 150; // 循环写入150次
  54. let count = 0;
  55. while (numBuffersToCapture) {
  56. let bufferSize = await this.audioCapturer.getBufferSize();
  57. let buffer = await this.audioCapturer.read(bufferSize, true);
  58. let options = {
  59. offset: count * bufferSize,
  60. length: bufferSize
  61. };
  62. if (buffer === undefined) {
  63. console.error(`${TAG}: read buffer failed`);
  64. } else {
  65. let number = fs.writeSync(fd, buffer, options);
  66. console.info(`${TAG}: write date: ${number}`);
  67. }
  68. numBuffersToCapture--;
  69. count++;
  70. }
  71. }
  72. // 停止采集
  73. async stop() {
  74. // 只有采集器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止
  75. if (this.audioCapturer.state !== audio.AudioState.STATE_RUNNING && this.audioCapturer.state !== audio.AudioState.STATE_PAUSED) {
  76. console.info('Capturer is not running or paused');
  77. return;
  78. }
  79. await this.audioCapturer.stop(); // 停止采集
  80. if (this.audioCapturer.state === audio.AudioState.STATE_STOPPED) {
  81. console.info('Capturer stopped');
  82. } else {
  83. console.error('Capturer stop failed');
  84. }
  85. }
  86. // 销毁实例,释放资源
  87. async release() {
  88. // 采集器状态不是STATE_RELEASED或STATE_NEW状态,才能release
  89. if (this.audioCapturer.state === audio.AudioState.STATE_RELEASED || this.audioCapturer.state === audio.AudioState.STATE_NEW) {
  90. console.info('Capturer already released');
  91. return;
  92. }
  93. await this.audioCapturer.release(); // 释放资源
  94. if (this.audioCapturer.state == audio.AudioState.STATE_RELEASED) {
  95. console.info('Capturer released');
  96. } else {
  97. console.error('Capturer release failed');
  98. }
  99. }
  100. }
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号