【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

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

相关推荐
Mintopia2 分钟前
一个月速成 AI 工程师:从代码小白到智能工匠的修炼手册
前端·javascript·aigc
Mintopia5 分钟前
Next.js 全栈:接收和处理请求
前端·javascript·next.js
tanyongxi6614 分钟前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式
遗憾皆是温柔17 分钟前
24. 什么是不可变对象,好处是什么
java·开发语言·面试·学习方法
wearegogog12337 分钟前
C语言中的输入输出函数:构建程序交互的基石
c语言·开发语言·交互
Fine姐40 分钟前
The Network Link Layer: 无线传感器中Delay Tolerant Networks – DTNs 延迟容忍网络
开发语言·网络·php·硬件架构
晓得迷路了1 小时前
栗子前端技术周刊第 94 期 - React Native 0.81、jQuery 4.0.0 RC1、Bun v1.2.20...
前端·javascript·react.js
江城开朗的豌豆1 小时前
React Native 实战心得
javascript
HAPPY酷1 小时前
给纯小白的Python操作 PDF 笔记
开发语言·python·pdf