HarmonyOS 鸿蒙Next SoundPool播放音频无声音
HarmonyOS 鸿蒙Next SoundPool播放音频无声音
使用soundPool播放mp3音频没有声音,代码如下
Button("播放拍摄音频").onClick(() => {
let audioManager = new AudioEffectHelper()
audioManager.loadRaw("camera_shutter.mp3")
.then((data) => {
setTimeout(() => {
audioManager.play()
audioManager.release()
}, 1000)
})
.catch((e: BusinessError) => {
showToast(e.message)
})
})
//////////////////////////////
import media from '@ohos.multimedia.media'
import audio from '@ohos.multimedia.audio'
import { Logger } from '@ohos/base'
import { HashMap } from '@kit.ArkTS'
export class AudioEffectHelper {
soundPool: media.SoundPool | undefined
//private _map: HashMap<string, number> = new HashMap()
id: number = -1
onLoadComplete?: (id: number) => void
private _map: HashMap<number, number> = new HashMap()
constructor() {
}
private async create(): Promise<boolean> {
try {
if (this.soundPool == undefined) {
this.soundPool = await media.createSoundPool(1, {
usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
rendererFlags: 1
})
}
this.soundPool.on('loadComplete', (id) => {
Logger.ERROR({
msg: "加载资源完成:" + id
})
//this.onLoadComplete?.(id)
this._map.set(id, id)
})
this.soundPool.on('playFinished', () => {
Logger.ERROR({
msg: "播放完成:"
})
})
this.soundPool.on('error', (error) => {
Logger.ERROR({
msg: "异常:" + JSON.stringify(error)
})
})
return this.soundPool != undefined
} catch (e) {
Logger.ERROR({
msg: "初始化soundPool失败:" + JSON.stringify(e)
})
return false
}
}
async loadRaw(file: string): Promise<boolean> {
Logger.ERROR({
msg: "loadRaw 开始:" + file
})
return this.create()
.then((data) => {
let raw = getContext().resourceManager.getRawFdSync(file)
return this.soundPool?.load(raw.fd, raw.offset, raw.length)
})
.then((data) => {
return data
})
.then((data) => {
this.id = data ?? -1
Logger.ERROR({
msg: "loadRaw 完成:" + data
})
return data != undefined && data != -1
})
// let raw = getContext().resourceManager.getRawFdSync(file)
// if (this.soundPool === undefined) {
// await this.create()
// }
// this.id = (await this.soundPool?.load(`fd://${raw.fd}`)) ?? -1
// return this.id != -1
}
async play(): Promise<boolean> {
Logger.ERROR({
msg: "play 开始:" + this.id
})
return this.soundPool?.play(this.id, {
loop: 0, // 循环0次
rate: 2, // 2倍速
leftVolume: 0.5, // range = 0.0-1.0
rightVolume: 0.5, // range = 0.0-1.0
priority: 0, // 最低优先级
})?.then((data) => {
Logger.ERROR({
msg: "play 完成:" + data
})
return data != 0
}) ?? false
// if (this.soundPool) {
// let playResult = await this.soundPool?.play(this.id, {
// loop: 1,
// leftVolume: 1,
// rightVolume: 1,
// rate: audio.AudioRendererRate.RENDER_RATE_NORMAL,
// })
// return playResult != 0
// } else {
// return false
// }
}
async release(): Promise<boolean> {
if (this.soundPool) {
return this.soundPool?.stop(this.id)
.then((data) => {
return this.soundPool?.unload(this.id)
})
.then((data) => {
return this.soundPool?.release()
})
.then((data) => {
return true
})
} else {
return true
}
}
}
更多关于HarmonyOS 鸿蒙Next SoundPool播放音频无声音的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
参考如下代码:
import audio from '[@ohos](/user/ohos).multimedia.audio';
import media from '[@ohos](/user/ohos).multimedia.media';
import fs from '[@ohos](/user/ohos).file.fs'
import picker from '[@ohos](/user/ohos).file.picker';
import { BusinessError } from '[@ohos](/user/ohos).base';
import { common } from '[@kit](/user/kit).AbilityKit';
let urii: string = '';
let soundPool: media.SoundPool;
let streamId: number = 0;
const audioSelectOptions = new picker.AudioSelectOptions();
let soundId: number = 0;
let audioRendererInfo: audio.AudioRendererInfo = {
usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
rendererFlags: 1
}
let PlayParameters: media.PlayParameters = {
loop: 3, // 循环4次
rate: audio.AudioRendererRate.RENDER_RATE_NORMAL, // 正常倍速
leftVolume: 0.9, // range = 0.0-1.0
rightVolume: 0.9, // range = 0.0-1.0
priority: 3, // 最低优先级
}
let uri: string = "";
[@Entry](/user/Entry)
[@Component](/user/Component)
struct NormalCapturer {
[@State](/user/State) message: string = '播放音频';
async aboutToAppear(): Promise<void> {
create();
}
async aboutToDisappear() {
release();
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button('播放音频').onClick((event: ClickEvent) => {
PlaySoundPool();
})
}
.width('100%')
}
.height('100%')
}
}
async function loadCallback() {
// 加载完成回调
soundPool.on('loadComplete', (soundId_: number) => {
console.info('loadComplete, soundId: ' + soundId_);
})
}
//设置播放完成监听
async function finishPlayCallback() {
// 播放完成回调
soundPool.on('playFinished', () => {
console.info("recive play finished message");
// 可进行下次播放
})
}
//设置错误类型监听
function setErrorCallback() {
soundPool.on('error', (error) => {
console.info('error happened,message is :' + error.message);
})
}
async function PlaySoundPool() {
console.log("开始播放");
// 开始播放,这边play也可带播放播放的参数PlayParameters
streamId = await soundPool.play(soundId,PlayParameters);
}
async function release() {
// 终止指定流的播放
soundPool.stop(streamId);
// 卸载音频资源
await soundPool.unload(soundId);
//关闭监听
setOffCallback();
// 释放SoundPool
await soundPool.release();
}
//关闭监听
function setOffCallback() {
soundPool.off('loadComplete');
soundPool.off('playFinished');
soundPool.off('error');
}
async function create() {
//创建soundPool实例
soundPool = await media.createSoundPool(5, audioRendererInfo);
console.log("音频类型为:" + audioRendererInfo.usage.valueOf())
//注册监听
loadCallback();
finishPlayCallback();
setErrorCallback();
// 加载音频资源
let context: common.UIAbilityContext = getContext() as common.UIAbilityContext;
let data = context.resourceManager.getRawFdSync('camera_shutter.mp3');
let sanboxPath = context.filesDir
console.log("沙箱路径:" + sanboxPath)
let filePath = context.tempDir + "/camera_shutter.mp3"
console.log("压缩文件路径:" + filePath)
let dest = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
let bufsize = 4096
let buf = new ArrayBuffer(bufsize)
let off = 0, len = 0, readedLen = 0
/**
* 通过buffer将rawfile文件内容copy到沙箱路径
*/
while (len = fs.readSync(data.fd, buf, { offset: data.offset + off, length: bufsize })) {
readedLen += len
fs.writeSync(dest.fd, buf, { offset: off, length: len })
off = off + len
if ((data.length - readedLen) < bufsize) {
bufsize = data.length - readedLen
}
}
fs.close(dest.fd)
context.resourceManager.closeRawFd("audio4Test.mp4", (err, data) => {
console.log("closeRawFd start")
if (err != null) {
console.log(err.message)
} else {
console.log("close success")
}
})
await fs.open(filePath, fs.OpenMode.READ_ONLY).then((file_: fs.File) => {
let file = file_;
console.info("file fd: " + file.fd);
uri = 'fd://' + (file.fd).toString()
});
soundPool.load(uri).then((soundIdd: number) => {
console.info('soundPool load uri success');
soundId = soundIdd;
}).catch((err: BusinessError) => {
console.error('soundPool load failed and catch error is ' + err.message);
})
}
更多关于HarmonyOS 鸿蒙Next SoundPool播放音频无声音的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
HarmonyOS 鸿蒙Next中,若使用SoundPool播放音频无声音,可能的原因及解决方案如下:
-
音频文件问题:
- 确认音频文件格式是否被SoundPool支持(如mp3, ogg)。
- 检查音频文件是否损坏或为空。
-
SoundPool配置:
- 验证SoundPool的初始化参数,特别是最大音频流数量和音频质量设置。
- 确保音频流的音量已正确设置,未设为静音或极低值。
-
音频焦点:
- 检查应用是否已正确请求并获取音频焦点。
- 如有其他应用正在播放音频,可能导致音频焦点冲突。
-
系统权限:
- 确认应用是否已获取必要的音频播放权限。
-
硬件与驱动:
- 检查设备音频硬件是否正常工作。
- 尝试更新设备驱动或系统至最新版本。
-
后台播放限制:
- 检查是否有后台播放限制策略影响音频播放。
如果上述方法均未能解决问题,请直接联系设备制造商或访问HarmonyOS官方论坛寻求帮助。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html。
回到顶部