使用AudioCapturer開發(fā)音頻錄制功能

2024-02-16 13:55 更新

AudioCapturer是音頻采集器,用于錄制PCM(Pulse Code Modulation)音頻數(shù)據(jù),適合有音頻開發(fā)經(jīng)驗(yàn)的開發(fā)者實(shí)現(xiàn)更靈活的錄制功能。

開發(fā)指導(dǎo)

使用AudioCapturer錄制音頻涉及到AudioCapturer實(shí)例的創(chuàng)建、音頻采集參數(shù)的配置、采集的開始與停止、資源的釋放等。本開發(fā)指導(dǎo)將以一次錄制音頻數(shù)據(jù)的過程為例,向開發(fā)者講解如何使用AudioCapturer進(jìn)行音頻錄制,建議搭配AudioCapturer的API說明閱讀。

下圖展示了AudioCapturer的狀態(tài)變化,在創(chuàng)建實(shí)例后,調(diào)用對(duì)應(yīng)的方法可以進(jìn)入指定的狀態(tài)實(shí)現(xiàn)對(duì)應(yīng)的行為。需要注意的是在確定的狀態(tài)執(zhí)行不合適的方法可能導(dǎo)致AudioCapturer發(fā)生錯(cuò)誤,建議開發(fā)者在調(diào)用狀態(tài)轉(zhuǎn)換的方法前進(jìn)行狀態(tài)檢查,避免程序運(yùn)行產(chǎn)生預(yù)期以外的結(jié)果。

圖1 AudioCapturer狀態(tài)變化示意圖

使用on('stateChange')方法可以監(jiān)聽AudioCapturer的狀態(tài)變化,每個(gè)狀態(tài)對(duì)應(yīng)值與說明見AudioState

開發(fā)步驟及注意事項(xiàng)

  1. 配置音頻采集參數(shù)并創(chuàng)建AudioCapturer實(shí)例,音頻采集參數(shù)的詳細(xì)信息可以查看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. 調(diào)用start()方法進(jìn)入running狀態(tài),開始錄制音頻。
    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. 指定錄制文件地址,調(diào)用read()方法讀取緩沖區(qū)的數(shù)據(jù)。
    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. 調(diào)用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. 調(diào)用release()方法銷毀實(shí)例,釋放資源。
    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 // 音頻采集器標(biāo)志
  15. }
  16. private audioCapturerOptions = {
  17. streamInfo: this.audioStreamInfo,
  18. capturerInfo: this.audioCapturerInfo
  19. }
  20. // 初始化,創(chuàng)建實(shí)例,設(shè)置監(jiān)聽事件
  21. init() {
  22. audio.createAudioCapturer(this.audioCapturerOptions, (err, capturer) => { // 創(chuàng)建AudioCapturer實(shí)例
  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事件,當(dāng)采集的幀數(shù)達(dá)到1000時(shí)觸發(fā)回調(diào)
  30. if (position === 1000) {
  31. console.info('ON Triggered successfully');
  32. }
  33. });
  34. this.audioCapturer.on('periodReach', 2000, (position) => { // 訂閱periodReach事件,當(dāng)采集的幀數(shù)達(dá)到2000時(shí)觸發(fā)回調(diào)
  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) { // 當(dāng)且僅當(dāng)狀態(tài)為STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一時(shí)才能啟動(dòng)采集
  45. console.error(`${TAG}: start failed`);
  46. return;
  47. }
  48. await this.audioCapturer.start(); // 啟動(dòng)采集
  49. let context = getContext(this);
  50. const path = context.filesDir + '/test.wav'; // 采集到的音頻文件存儲(chǔ)路徑
  51. let file = fs.openSync(path, 0o2 | 0o100); // 如果文件不存在則創(chuàng)建文件
  52. let fd = file.fd;
  53. let numBuffersToCapture = 150; // 循環(huán)寫入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. // 只有采集器狀態(tài)為STATE_RUNNING或STATE_PAUSED的時(shí)候才可以停止
  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. // 銷毀實(shí)例,釋放資源
  87. async release() {
  88. // 采集器狀態(tài)不是STATE_RELEASED或STATE_NEW狀態(tài),才能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. }
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)