HarmonyOS鸿蒙Next中分享AudioCapturer采集的录音

发布于 1周前 作者 eggper 来自 鸿蒙OS

HarmonyOS鸿蒙Next中分享AudioCapturer采集的录音 在分享AudioCapturer采集的录音的时候,分享过后无法播放录音

let contexts = getContext(this).getApplicationContext();
let path = contexts.filesDir;
// const filePath =  path + `/${item.recordingSong}.mp3`;

const contextFaker: Context = getContext(this);
const filePath =  path + `${item.recordingSong}.mp3`; 

// let filePath = contextFaker.filesDir + '/exampleVideo.mp4';//路径
/** Solution 1 */
const resourceMgr: resourceManager.ResourceManager = contextFaker.resourceManager;
const fileData: Uint8Array = await resourceMgr.getMediaContent($r('app.media.app_icon'));
this.thumbnailBuffer = fileData;
/** Solution 2 */
// let thumbnailPath = contextFaker.filesDir + '/exampleImage.jpg'; //图片路径
// const imageSource: image.ImageSource = image.createImageSource(thumbnailPath);
// const imagePacker: image.ImagePacker = image.createImagePacker();
// const buffer: ArrayBuffer = await imagePacker.packToData(imageSource, {
//   format: 'image/jpeg',
//   quality: 30,
// });
// this.thumbnailBuffer = new Uint8Array(buffer);
// let utdTypeId = utd.getUniformDataTypeByFilenameExtension('.mp3', utd.UniformDataType.MP3);
// let utdTypeId = utd.getUniformDataTypeByFilenameExtension('.mp3',  utd.UniformDataType.MP3);
let shareData: systemShare.SharedData = new systemShare.SharedData({
  utd: utd.UniformDataType.PCM,
  // utd: utdTypeId,
  uri: fileUri.getUriFromPath(filePath),
  title: '111',
  description: `${item.recordingSong}`,
  thumbnail: this.thumbnailBuffer,
});
let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
const callback = () => {
  // Log.info('HuaweiShare_ dismiss run');
  console.log('-=-=:HuaweiShare_ dismiss run')
  promptAction.showToast({ message: 'Share panel disappeared' });
};
controller.on('dismiss', callback);
// controller.off('dismiss', callback);
console.log(`-=-=:dismiss', callback`)
let context = getContext(this) as common.UIAbilityContext;
controller.show(context, {
  previewMode: this.videoPreviewMode === 0 ? systemShare.SharePreviewMode.DEFAULT : systemShare.SharePreviewMode.DETAIL
}).then(() => {
  // logger.info('HuaweiShare_ show');
  console.log(`-=-=:HuaweiShare_ show`)
}).catch((error: BusinessError) => {
  // logger.error(`HuaweiShare_ show error. Code: ${error.code}, message: ${error.message}`);
  console.log(`HuaweiShare_ show error. Code: ${error.code}, message: ${error.message}`)
});

更多关于HarmonyOS鸿蒙Next中分享AudioCapturer采集的录音的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

7 回复

录音采集pcm转wav方法

import fs, { ReadOptions } from '@ohos.file.fs';
export class PcmToWavUtil {
  //采样率
  private mSampleRate: number = 0
  // 声道数
  private mChannel: number = 0;

  /**
   * @param sampleRate  sample rate、采样率
   * @param channel     channel、声道
   */
  constructor(sampleRate:number, channel: number) {
    this.mSampleRate = sampleRate;
    this.mChannel = channel;
  }

  /**
   * pcm文件转wav文件函数
   * @param src  源文件
   * @param dest 目标文件
   */
  public pcmToWav(src: string, dest: string) {
    const inFile: fs.File = fs.openSync(src, fs.OpenMode.READ_ONLY);
    const outFile: fs.File = fs.openSync(dest, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    let byteRate = 16 * this.mSampleRate * this.mChannel / 8;
    let inFileStat = fs.statSync(inFile.fd)
    // 音频文件
    let audioDataSize = inFileStat.size;
    let totalDataLen = audioDataSize + 36;
    // 1. wav 文件头编写
    this.writeWaveFileHeader(outFile, audioDataSize, totalDataLen, byteRate);
    // 2. 写入 pcm 数据
    this.writePcmData(inFile, outFile, audioDataSize)
  }

  // pcm 数据写入到 pcm 文件函数
  private writePcmData(inFile: fs.File, outFile: fs.File, audioDataSize: number) {
    // 写入 pcm 数据
    let readSize = 0
    let data = new ArrayBuffer(audioDataSize);
    let readOptions: ReadOptions = {
      offset: readSize,
      length: audioDataSize
    };
    let readLen = fs.readSync(inFile.fd, data, readOptions);
    while (readLen > 0) {
      readSize += readLen;
      fs.writeSync(outFile.fd, data, { length: readLen});
      readOptions.offset = readSize;
      readLen = fs.readSync(inFile.fd, data, readOptions);
    }
    fs.closeSync(inFile.fd)
    fs.closeSync(outFile.fd)
  }

  //写入wav文件头函数
  private writeWaveFileHeader(
    out: fs.File,
    audioDataSize: number,
    totalDataLen: number,
    byteRate: number
  ) {
    const header = new ArrayBuffer(44);
    const dv = new DataView(header);
    const bitsPerSample = 16; // 当前位深是16

    // 写入RIFF块
    this.writeString(dv, 0, 'RIFF');
    dv.setUint32(4, totalDataLen, true);
    this.writeString(dv, 8, 'WAVE');

    // 写入fmt块
    this.writeString(dv, 12, 'fmt ');
    dv.setUint32(16, 16, true); // fmt块大小
    dv.setUint16(20, 1, true); // 格式类别 (PCM)
    dv.setUint16(22, this.mChannel, true); // 通道数
    dv.setUint32(24, this.mSampleRate, true); // 采样率
    dv.setUint32(28, byteRate, true); // ByteRate 码率
    dv.setUint16(32, this.mChannel * bitsPerSample / 8, true); // BlockAlign
    dv.setUint16(34, bitsPerSample, true); // 位深

    // 写入data块
    this.writeString(dv, 36, 'data');
    dv.setUint32(40, audioDataSize, true); // 数据块大小
    // 写入
    fs.writeSync(out.fd, new Uint8Array(header).buffer, {
      length: 44
    })
  }

  private writeString(dv: DataView, offset: number, str: string) {
    for (let i = 0; i < str.length; i++) {
      dv.setUint8(offset + i, str.charCodeAt(i));
    }
  }
}

更多关于HarmonyOS鸿蒙Next中分享AudioCapturer采集的录音的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


你好,请问是在使用audioCapturer.start开始录音完成后,无法播放吗?

有没有对应报错信息呢?如果有麻烦补充一下,另外可以检查一下有没有申请MICROPHONE权限。比如:

```javascript
onWindowStageCreate(windowStage: window.WindowStage) {
  // Main window is created, set main page for this ability
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
  let atManager = abilityAccessCtrl.createAtManager();
  atManager.requestPermissionsFromUser(this.context, ['ohos.permission.MICROPHONE']).then((data) => {
    console.info('data:' + JSON.stringify(data));
    console.info('data permissions:' + data.permissions);
    console.info('data authResults:' + data.authResults);
  }).catch((err) => {
    console.info('data:' + JSON.stringify(err));
  });
  windowStage.loadContent('pages/Index', (err, data) => {
    if (err.code) {
      hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
      return;
    }
    hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
  })
}

我这边是可以录音,这段录音也可以播放,但是分享出去的那段录音无法播放,

这段分享出来的录音,无法在手机里面播放,

分享是怎么分享的?

在HarmonyOS鸿蒙Next中,分享通过AudioCapturer采集的录音数据可以通过以下步骤实现:

  1. 初始化AudioCapturer:首先,使用AudioCapturer类初始化音频采集器,配置参数如采样率、声道数、音频格式等。

  2. 采集音频数据:启动AudioCapturer后,通过read方法从音频硬件中读取数据,数据存储在缓冲区中。

  3. 处理音频数据:对采集到的音频数据进行必要的处理,如编码、压缩等。

  4. 保存音频文件:将处理后的音频数据保存为文件,如WAV、MP3等格式。

  5. 分享音频文件:使用HarmonyOS的分享功能,通过Intent将音频文件分享到其他应用或设备。可以使用Share API,指定文件URI和分享类型。

示例代码如下:

import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

// 初始化AudioCapturer
let audioCapturer = new audio.AudioCapturer({
  audioStreamInfo: {
    samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
    channels: audio.AudioChannel.CHANNEL_2,
    sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
    encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
  },
  capturerInfo: {
    source: audio.SourceType.SOURCE_TYPE_MIC,
    capturerFlags: 0
  }
});

// 启动采集
audioCapturer.start();

// 读取音频数据
let bufferSize = 4096;
let buffer = new ArrayBuffer(bufferSize);
audioCapturer.read(buffer, bufferSize, false);

// 保存为文件
let filePath = '/data/storage/el2/base/cache/audio.wav';
let fd = fileio.openSync(filePath, 0o102, 0o666);
fileio.writeSync(fd, buffer);
fileio.closeSync(fd);

// 分享文件
let intent = {
  action: 'ohos.intent.action.SEND',
  uri: 'file://' + filePath,
  type: 'audio/wav'
};
featureAbility.startAbility(intent);

// 停止采集
audioCapturer.stop();

在HarmonyOS鸿蒙Next中,使用AudioCapturer采集音频数据后,可以通过File类将数据写入文件进行保存,或者通过Intent分享到其他应用。首先,确保权限已获取,然后使用AudioCapturer采集音频数据。采集完成后,将数据写入文件,并通过Intent设置文件URI,调用startActivity进行分享。具体实现需参考HarmonyOS API文档和开发指南。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!