【Harmony】@ohos.multimedia.audioHaptic (音振协同)填坑版~7

音振协同,表示在播放声音时,可同步发起振动。可用于来电通知、消息提醒等场景

导入模块

typescript 复制代码
import { audioHaptic } from '@kit.AudioKit';audioHaptic.getAudioHapticManagergetAudioHapticManager():

AudioHapticManager获取音振管理器。系统能力: SystemCapability.Multimedia.AudioHaptic.Core

typescript 复制代码
 let audioHapticManagerInstance: audioHaptic.AudioHapticManager = audioHaptic.getAudioHapticManager();

AudioHapticManager管理音振协同功能。

在调用AudioHapticManager的接口前registerSourceregisterSource(audioUri: string, hapticUri: string): Promise注册音频和振动资源的Uri,使用Promise方式异步返回结果。

typescript 复制代码
import { BusinessError } from '@kit.BasicServicesKit';
let audioUri = 'data/audioTest.wav'; // 需更改为目标音频资源的Urilet hapticUri = 'data/hapticTest.json'; // 需更改为目标振动资源的Urilet id = 0;
audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);  id = value;}).catch ((err: BusinessError) => {  console.error(`Failed to register source ${err}`);});

以上摘抄官网部分使用说明

官网 demo 代码如下:

typescript 复制代码
import { BusinessError } from '@kit.BasicServicesKit';
let audioUri = 'data/audioTest.wav'; // 需更改为目标音频资源的Urilet hapticUri = 'data/hapticTest.json'; // 需更改为目标振动资源的Urilet id = 0;
audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);  id = value;}).catch ((err: BusinessError) => {  console.error(`Failed to register source ${err}`);});
let options: audioHaptic.AudioHapticPlayerOptions = {muteAudio: false, muteHaptics: false};let audioHapticPlayerInstance: audioHaptic.AudioHapticPlayer | undefined = undefined;
audioHapticManagerInstance.createPlayer(id, options).then((value: audioHaptic.AudioHapticPlayer) => {  audioHapticPlayerInstance = value;  console.info(`Create the audio haptic player successfully.`);}).catch ((err: BusinessError) => {  console.error(`Failed to create the audio haptic player. ${err}`);});

看上去也没有啥困难的。事实上也的确不难

坑位

但坑就出在那个文件路径上'data/audioTest.wav';这个是 string 类型的路径而项目一般都会把文件放到 rawfile 资源目录里,然后问题来了,怎么获取到 rawfile 里文件的路径地址了,我找了半天也没有找到,然后找了几个同事也没有发现。结果是花了两天也没有找到好的办法

突破点:

registerSource需要的是 string 类型的路径地址;那给它一个路径文件地址就可以了。于是开始了骚操作如下:

1、使用沙箱定义路径地址:

typescript 复制代码
let audioUriPath = getContext().cacheDir + '/audioTest.mp3';let hapticUriPath = getContext().cacheDir + '/hapticTest.json';

这样就有了地址了

2、使用resourceManager 调用getRawFileContentSync读取内容

typescript 复制代码
let audioUriConte = getContext().resourceManager.getRawFileContentSync('audioTest.mp3');let hapticUriConte = getContext().resourceManager.getRawFileContentSync('hapticTest.json'); 

3、然后使用文件写入到定义的文件路径地址里

typescript 复制代码
FileUtils.writeFileOnlyOne(audioUriPath, audioUriConte);FileUtils.writeFileOnlyOne(hapticUriPath, hapticUriConte);

附一份

typescript 复制代码
FileUlteimport { fileIo as fs } from '@kit.CoreFileKit';

const TAG='[FileUtils]'

export namespace FileUtils{  

export function writeFileOnlyOne(filePath: string, content: Uint8Array) { 

try {      
let res=fs.accessSync(filePath)      

if(res){        
console.debug(TAG,'已存在 audioUriPath='+filePath)        
return          }       
 } catch (e) {          
console.debug(TAG,JSON.stringify(e))              
}             

 console.debug(TAG,'writeFile called!-start writing')                  
      writeFile(filePath,content)  }             
export function writeFile(filePath: string, content: Uint8Array){        
       
       const file: fs.File = fs.openSync(filePath                 , fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);               
       fs.writeSync(file.fd, content.buffer);              
        fs.closeSync(file);             
        }
    }

其他就回到官方使用说明里走逻辑流程即可===================END

如果对老师您有点用,可否用发财的金手指点个赞👍

相关推荐
To_OC6 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
灯澜忆梦7 小时前
GO_并发编程---定时器
开发语言·后端·golang
-银雾鸢尾-7 小时前
C#中的StringBuilder相关方法
开发语言·c#
To_OC8 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn8 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
-银雾鸢尾-8 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
এ慕ོ冬℘゜8 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
大模型码小白9 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
随心点儿9 小时前
js postMessage 实现跨域发送消息-应用示例
javascript·ecmascript·postmessage
kyriewen11 小时前
我让AI改一个bug——它偷偷动了5个我没让它碰的地方
前端·javascript·ai编程