音频容器规格 | 规格描述 |
|---|---|
m4a | 音频格式:AAC。 |
aac | 音频格式:AAC。 |
mp3 | 音频格式:MP3。 |
ogg | 音频格式:VORBIS。 |
wav | 音频格式:PCM。 |
10-28 14:50:41.901 com.examp...graphics I [IncSoundData][[102076]RendererInClient] channel: 2, L=1630, R=1661, counts: 400 10-28 14:50:43.905 com.examp...graphics I [IncSoundData][[102076]RendererInClient] channel: 2, L=3776, R=3873, counts: 500 10-28 14:50:44.864 com.examp...graphics I #362 CacheBuffer stream write finish, cacheDataFrameIndex_:1050624, havePlayedCount_:0, loop:0, streamID_:1, length: 1920 10-28 14:50:44.865 com.examp...graphics I #449 CacheBuffer::Stop soundID_:1, streamID:1 10-28 14:50:44.866 com.examp...graphics I #463 audioRenderer normal stop. 10-28 14:50:44.866 com.examp...graphics I StreamClientState for Renderer::Stop. id: 102076 10-28 14:50:44.866 com.examp...graphics I [WriteUnderrunEvent]AudioRendererPrivate WriteUnderrunEvent! 10-28 14:50:44.866 com.examp...graphics I [StopAudioStream]Stop begin for sessionId 102076 uid: 20020275
loadCallback(soundPool: media.SoundPool) {
soundPool.on('loadComplete', (soundId: number) => {
console.info('loadComplete, soundId: ' + soundId);
});
} import { media } from '@kit.MediaKit';
import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';
let soundPool: media.SoundPool;
@ObservedV2
class SoundFile {
@Trace
filename: string = '';
@Trace
soundId: number = -1;
constructor(filename: string, soundId: number) {
this.filename = filename;
this.soundId = soundId;
}
}
@Builder
export function PageBuilder() {
TestPage();
}
@Entry
@ComponentV2
struct TestPage {
private context: Context = this.getUIContext().getHostContext() as Context;
@Local soundFilesArr: Array<SoundFile> = new Array();
async aboutToAppear(): Promise<void> {
await this.create();
}
build() {
NavDestination() {
Column({ space: 2 }) {
List({ space: 2 }) {
ForEach(this.soundFilesArr, (item: SoundFile, index: number) => {
ListItem() {
Row({ space: 1 }) {
Text(index + 1 + '-' + item.filename);
Button('加载')
.onClick(async () => {
await this.load(item.filename);
})
Button(`播放${item.soundId > 0 ? 'Ready' : 'UnReady'}`)
.onClick(async () => {
await this.play(item.soundId);
})
Button('卸载')
.onClick(async () => {
await this.unload(item.filename, item.soundId);
})
}
}
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
async create() {
// 创建soundPool实例
let audioRendererInfo: audio.AudioRendererInfo = {
usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // 音频流使用类型:音乐。根据业务场景配置,参考StreamUsage
rendererFlags: 1 // 音频渲染器标志
};
try {
soundPool = await media.createSoundPool(32, audioRendererInfo);
} catch (error) {
console.error('load raw file error ' + JSON.stringify(error));
}
this.loadCallback(soundPool); // 监听loadComplete
await this.scanRawFile(); // 扫描rawfile音频资源
}
async scanRawFile() {
try {
let resourceManager = this.context.resourceManager;
let files = await resourceManager.getRawFileList('soundpool/'); //确保目录存在,并包含音频文件
for (let i = 0; i < files.length; i++) {
let soundFile: SoundFile = new SoundFile(files[i], -1);
this.soundFilesArr.push(soundFile);
}
} catch (error) {
console.error('getRawFileList error' + JSON.stringify(error));
}
}
async load(fileName: string) {
try {
let rowFd = await this.context.resourceManager.getRawFd('soundpool/' + fileName);
console.info('file uri: ' + fileName + ',' + rowFd.fd);
await soundPool.load(rowFd.fd, rowFd.offset, rowFd.length).then((soundId) => {
this.updListArrSoundId(fileName, soundId);
})
.catch((e: BusinessError) => {
console.error('load sound err: ', e.code, e.message);
});
} catch (error) {
console.error('load raw file error' + JSON.stringify(error));
}
}
async play(soundId: number) {
// 开始播放,这边play也可带播放的参数PlayParameters,请在音频资源加载完毕,即收到loadComplete回调之后再执行play操作
await soundPool.play(soundId).then(async (streamId: number) => {
console.info('play sound success soundid:' + soundId, streamId);
}, (err: BusinessError) => {
console.info(`play sound Error: errCode is ${err.code}, errMessage is ${err.message}`);
});
}
async unload(fileName: string, soundId: number) {
soundPool.unload(soundId, (error: BusinessError) => {
if (error) {
console.error(`Failed to unload soundPool: errCode is ${error.code}, errMessage is ${error.message}`, soundId);
} else {
console.info('Succceeded in unload soundPool', soundId);
this.updListArrSoundId(fileName, -1);
}
});
}
loadCallback(soundPool: media.SoundPool) {
soundPool.on('loadComplete', (soundId: number) => {
console.info('loadComplete, soundId: ' + soundId);
});
}
updListArrSoundId(fileName: string, soundId: number) {
// 更新list记录soundId
this.soundFilesArr.forEach((soundFile) => {
if (soundFile.filename == fileName) {
soundFile.soundId = soundId;
}
});
};
} 使用SoundPool音频播放时,需正确按照组件规格进行调用,并遵守SoundPool播放顺序,详情参考官网完整示例。