HarmonyOS 录制音频后的文件如何通过接口上传,现在索引不到资源文件

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

可以采用axios上传文件,不需要picker选择,demo参考:

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
import fs from '@ohos.file.fs';
import axios, { AxiosError, AxiosProgressEvent, AxiosResponse } from '@ohos/axios'
import { FormData } from '@ohos/axios'

const TAG = 'AudioCapturerDemo';

class Options {
  offset?: number;
  length?: number;
}

let context = getContext(this);
let bufferSize: number = 0;
let audioCapturer: audio.AudioCapturer | undefined = undefined;
let audioStreamInfo: audio.AudioStreamInfo = {
  samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // 采样率
  channels: audio.AudioChannel.CHANNEL_2, // 通道
  sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // 采样格式
  encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // 编码格式
}
let audioCapturerInfo: audio.AudioCapturerInfo = {
  source: audio.SourceType.SOURCE_TYPE_MIC, // 音源类型
  capturerFlags: 0 // 音频采集器标志
}
let audioCapturerOptions: audio.AudioCapturerOptions = {
  streamInfo: audioStreamInfo,
  capturerInfo: audioCapturerInfo
}

const RANDOM_NUM = 10000;
let path = getContext().cacheDir;
let filePath: string;
let file: fs.File;

let readDataCallback = (buffer: ArrayBuffer) => {

  let options: Options = {
    offset: bufferSize,
    length: buffer.byteLength
  }
  console.debug("buffer=" + buffer)
  fs.writeSync(file.fd, buffer, options);
  console.debug("filePath=" + filePath);
  bufferSize += buffer.byteLength;
}

// 初始化,创建实例,设置监听事件
function init() {
  filePath = path + `/${getDate(2)}_${Math.floor(Math.random() * RANDOM_NUM)}.wav` ;
  file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  audio.createAudioCapturer(audioCapturerOptions, (err, capturer) => { // 创建AudioCapturer实例
    if (err) {
      console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`);
      return;
    }
    console.info(`${TAG}: create AudioCapturer success`);
    audioCapturer = capturer;
    if (audioCapturer !== undefined) {
      (audioCapturer as audio.AudioCapturer).on('readData', readDataCallback);
    }
  });
}

// 开始一次音频采集
function start() {
  if (audioCapturer !== undefined) {
    let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED];
    if (stateGroup.indexOf((audioCapturer as audio.AudioCapturer).state.valueOf()) === -1) { // 当且仅当状态为STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一时才能启动采集
      console.error(`${TAG}: start failed`);
      return;
    }
    // 启动采集
    (audioCapturer as audio.AudioCapturer).start((err: BusinessError) => {
      if (err) {
        console.error('Capturer start failed.');
      } else {
        console.info('Capturer start success.');
      }
    });
  }
}

// 停止采集
function stop() {
  if (audioCapturer !== undefined) {
    // 只有采集器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止
    if ((audioCapturer as audio.AudioCapturer).state.valueOf() !== audio.AudioState.STATE_RUNNING && (audioCapturer as audio.AudioCapturer).state.valueOf() !== audio.AudioState.STATE_PAUSED) {
      console.info('Capturer is not running or paused');
      return;
    }
    //停止采集
    (audioCapturer as audio.AudioCapturer).stop((err: BusinessError) => {
      if (err) {
        console.error('Capturer stop failed.');
      } else {
        // fs.close(file);
        console.info('Capturer stop success.');
      }
    });
  }
}

// 销毁实例,释放资源
function release() {
  if (audioCapturer !== undefined) {
    // 采集器状态不是STATE_RELEASED或STATE_NEW状态,才能release
    if ((audioCapturer as audio.AudioCapturer).state.valueOf() === audio.AudioState.STATE_RELEASED || (audioCapturer as audio.AudioCapturer).state.valueOf() === audio.AudioState.STATE_NEW) {
      console.info('Capturer already released');
      return;
    }
    //释放资源
    (audioCapturer as audio.AudioCapturer).release((err: BusinessError) => {
      if (err) {
        console.error('Capturer release failed.');
      } else {
        fs.close(file);
        console.info('Capturer release success.');
      }
    });
  }
}

function uploadFile() {
  let formData = new FormData()
  let fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
  console.log('internal://cache/'+fileName)
  formData.append('file', 'internal://cache/'+fileName)
  console.log('formData append end');
  // 发送请求
  console.log('axios post start');
  axios.post<string, AxiosResponse<string>, FormData>('https://www.index.com/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
    context: context,
    onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
      console.info(progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%');
    },
  }).then((res: AxiosResponse<string>) => {
    console.info("result" + JSON.stringify(res.data));
  }).catch((err: AxiosError) => {
    console.error("error:" + JSON.stringify(err));
  })
  console.log('axios post end');
}

function getDate(mode: number): string {
  let date = new Date();
  if (mode === 1) {
    return `${date.getFullYear()}/${formatNumber(date.getMonth() + 1)}/${formatNumber(date.getDate())}`;
  } else {
    return `${date.getFullYear()}${formatNumber(date.getMonth() + 1)}${formatNumber(date.getDate())}`;
  }
}

function formatNumber(num: number): string {
  if (num <= 9) {
    return '0' + num;
  } else {
    return '' + num;
  }
}

@Entry
@Component
struct AudioCapturerPage{
  build() {
    Column() {
      Row() {
        Button('初始化录音')
          .onClick(() => {
            init()
          })
      }
      .width('100%')
      .margin(50)
      .justifyContent(FlexAlign.Center)
      Row() {
        Button('开始录音')
          .onClick(() => {
            start()
          })
      }
      .width('100%')
      .margin(50)
      .justifyContent(FlexAlign.Center)
      Row() {
        Button('暂停录音')
          .onClick(() => {
            stop()
          })
      }
      .width('100%')
      .margin(50)
      .justifyContent(FlexAlign.Center)
      Row() {
        Button('结束录音')
          .onClick(() => {
            release()
          })
      }
      .width('100%')
      .margin(50)
      .justifyContent(FlexAlign.Center)
      Row() {
        Button('上传录音')
          .onClick(() => {
            uploadFile()
          })
      }
      .width('100%')
      .margin(50)
      .justifyContent(FlexAlign.Center)
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
如何获取HSP资源文件
2404浏览 • 1回复 待解决
鸿蒙如何获取资源文件路径
16524浏览 • 3回复 待解决
如何获取资源文件全路径
1977浏览 • 1回复 待解决
HarmonyOS 文件上传 & 资源读取问题
594浏览 • 1回复 待解决
HarmonyOS 资源文件无法跨模块访问
102浏览 • 1回复 待解决
如何获取profile路径下资源文件
1839浏览 • 1回复 待解决
ArkTS如何自定义资源文件
2283浏览 • 1回复 待解决
自定义资源文件怎么读取?
2422浏览 • 1回复 待解决
HarmonyOS 加载RN沙盒路径资源文件
191浏览 • 1回复 待解决