HarmonyOS H5拉起系统录音能力的样例代码

H5拉起系统录音能力的样例代码。

HarmonyOS
2024-10-28 10:50:16
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

​可以使用javaScriptProxy()接口或registerJavaScriptProxy()接口实现h5页面与arkts的交互,从而调用音频录能力制相关api。

相关参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/web-in-app-frontend-page-function-invoking-V5

https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-arkweb-kit-V5?catalogVersion=V5

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/2_3_u97f3_u9891_u5f55_u5236-V5

参考demo:​

import web_webview from '@ohos.web.webview';  
import business_error from '@ohos.base';  
import {AudioC} from '../util/audioClass'  
import {AudioRendererC} from '../util/AudioRendererClass'  
import { common, abilityAccessCtrl } from '@kit.AbilityKit';  
@Entry  
@Component  
struct Index {  
  webviewController: web_webview.WebviewController = new web_webview.WebviewController();  
  @State aa:AudioC = new AudioC();  
  @State rr:AudioRendererC = new AudioRendererC()  
  @State userGrant: boolean = false  
  
  async reqPermissionsFromUser(): Promise<number[]> {  
    console.info( 'reqPermissionsFromUser start ')  
    let context = getContext() as common.UIAbilityContext;  
    let atManager = abilityAccessCtrl.createAtManager();  
    let grantStatus = await atManager.requestPermissionsFromUser(context, ['ohos.permission.MICROPHONE']);  
    return grantStatus.authResults;  
  }  
  
  // 申请权限  
  async requestLocationPermission() {  
    let grantStatus = await this.reqPermissionsFromUser()  
    for (let i = 0; i < grantStatus.length; i++) {  
      if (grantStatus[i] === 0) {  
        // 用户授权,可以继续访问目标操作  
        console.info( 'requestPermissionsFromUser success');  
        this.userGrant = true;  
      }  
    }  
  }  
  async aboutToAppear() {  
    await this.requestLocationPermission().then((data)=>{  
      if (this.userGrant) {  
        this.aa.init()  
        this.rr.init()  
      }  
    })  
    try {  
      this.webviewController.registerJavaScriptProxy(this.aa, "aaName", ["init","start","stop","release"]);  
      this.webviewController.registerJavaScriptProxy(this.rr, "rrName", ["init","start","pause","release"]);  
      this.webviewController.refresh();  
    } catch (error) {  
      let e: business_error.BusinessError = error as business_error.BusinessError;  
      console.error(`ErrorCode: ${e.code}, Message: ${e.message}`);  
    }  
  }  
  build() {  
    Column({space:20}) {  
      Web({ src: $rawfile('index.html'), controller: this.webviewController })  
    }  
  }  
}
<!-- index.html -->  
<!DOCTYPE html>  
<html>  
<head>  
    <title>Hello World</title>  
    <style>  
        button {  
        width:300px;  
        height:100px;  
        background-color: #008CBA;  
        padding: 15px 30px;  
        text-align: center;  
        text-decoration: none;  
        font-size: 20px;  
        color: white;  
        }  
        div {  
        padding: 15px 30px;  
        text-align: center;  
        width:100%;  
        }  
    </style>  
</head>  
<body>  
<div>  
    <button type="button" onclick="start()">开始录制!</button>  
    <button type="button" onclick="stop()">结束录制!</button>  
</div>  
<div>  
    <button style="background-color: #555555" type="button" onclick="startR()">开始播放!</button>  
    <button style="background-color: #555555" type="button" onclick="stopR()">停止播放!</button>  
</div>  
  
<p id="demo"></p>  
<script>  
    function start() {  
    aaName.start();  
    console.info('start ok:');  
    }  
    function stop() {  
    aaName.stop();  
    console.info('stop ok:');  
    }  
    function startR() {  
    rrName.start();  
    console.info('startR ok:');  
    }  
    function stopR() {  
    rrName.pause();  
    console.info('stopR ok:');  
    }  
</script>  
</body>  
</html>

音频录制相关demo。

import audio from '@ohos.multimedia.audio';  
import { BusinessError } from '@ohos.base';  
import fs from '@ohos.file.fs';  
import promptAction from '@ohos.promptAction';  
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_44100,  
  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  
}  
let readDataCallback = (buffer: ArrayBuffer) => {  
  let path = getContext().cacheDir;  
  let filePath = path + '/StarWars10s-2C-48000-4SW.wav';  
  let file: fs.File = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);  
  let options: Options = {  
    offset: bufferSize,  
    length: buffer.byteLength  
  }  
  fs.writeSync(file.fd, buffer, options);  
  bufferSize += buffer.byteLength;  
}  
export class AudioC {  
  // 初始化,创建实例,设置监听事件  
  init() {  
    audio.createAudioCapturer(audioCapturerOptions).then((data) => {  
      audioCapturer = data;  
      console.info('AudioCapturer Created : Success : Stream Type: SUCCESS');  
      if (audioCapturer !== undefined) {  
        (audioCapturer as audio.AudioCapturer).on('readData', readDataCallback);  
      }  
    }).catch((err: BusinessError) => {  
      console.error(`AudioCapturer Created : ERROR : ${err.code}`);  
    });  
  }  
  // 开始一次音频采集  
  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('AudioCapturerDemo start failed');  
        return ;  
      }  
  
      // 启动采集  
      (audioCapturer as audio.AudioCapturer).start((err: BusinessError) => {  
        if (err) {  
          console.error('Capturer start failed.');  
          promptAction.showToast({  
            message:'开启失败'  
          })  
        } else {  
          console.info('Capturer start success.');  
          promptAction.showToast({  
            message:'开始录音'  
          })  
        }  
      });  
    }else {  
      console.info('Capturer start failed');  
    }  
  }  
  // 停止采集  
  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 {  
          this.release()  
          console.info('Capturer stop success.');  
        }  
      });  
    }  
  }  
  // 销毁实例,释放资源  
  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 {  
          console.info('Capturer release success.');  
          promptAction.showToast({  
            message:'录音结束'  
          })  
        }  
      });  
    }  
  }  
}

​代码中引入的AudioRendererClass为音频播放class (import {AudioRendererC} from '../util/AudioRendererClass')。在h5中调用逻辑与录制相似。

音频播放完整demo参考:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/using-audiorenderer-for-playback-V5

分享
微博
QQ
微信
回复
2024-10-28 15:01:18
相关问题
HarmonyOS H5拉起系统相机代码
198浏览 • 1回复 待解决
HarmonyOS web组件加载h5h5拉起摄像头
514浏览 • 1回复 待解决
HarmonyOS h5拉起系统扫码页面的demo
147浏览 • 1回复 待解决
HarmonyOS H5代码如何复用?
125浏览 • 1回复 待解决
HarmonyOS 应用涉及H5代码,如何使用?
167浏览 • 1回复 待解决
HarmonyOS 应用拉起系统录音
438浏览 • 1回复 待解决
HarmonyOS webview h5localstorage
346浏览 • 1回复 待解决
HarmonyOS 应用并发同步代码
358浏览 • 1回复 待解决
H5通过url scheme拉起对应应用
479浏览 • 1回复 待解决
HarmonyOS 能否提供Web工程代码
147浏览 • 1回复 待解决
Web能直接加载h5代码吗?
3006浏览 • 2回复 待解决
如何调试H5代码,有人知道吗?
1559浏览 • 1回复 待解决
跨平台开发,h5代码怎么调试?
177浏览 • 1回复 待解决
eTS求助 tabBarIcon代码
5786浏览 • 1回复 待解决
HarmonyOS 折叠屏H5适配问题
695浏览 • 1回复 待解决