
面试考官邢老师为您分享以下优质知识
二进制文件播放声音的方法主要分为以下两种情况,分别适用于不同的技术场景:
一、通过文件系统写入临时文件播放
使用 `uni.getFileSystemManager().writeFile()` 将二进制音频数据写入本地临时文件。此方法适用于小程序端,但需注意该函数在 App 端不支持。
播放临时文件
通过 `uni.createInnerAudioContext().play()` 直接播放已写入的临时音频文件。例如:
```javascript
uni.getFileSystemManager().writeFile({
filePath: '/tmp/audio.mp3',
data: binaryData,
encoding: 'base64',
success: function (res) {
const innerAudio = uni.createInnerAudioContext();
innerAudio.src = `/tmp/audio.mp3`;
innerAudio.play();
}
});
```
二、直接播放内存中的二进制数据
使用 `PlaySoundData` API
在 Windows 环境下,可通过 `winmm.dll` 提供的 `PlaySoundData` 函数直接播放内存中的二进制音频数据。需将二进制数据转换为 `lpData` 格式,并指定采样率、位深度等参数。例如:
```c
include
include
include
HRESULT PlayBinaryAudio(const BYTE* audioData, DWORD dataSize, DWORD sampleRate, DWORD bitsPerSample) {
IMMDeviceEnumerator* pEnumerator = NULL;
IMMDevice* pDevice = NULL;
IMMNotificationClient* pNotificationClient = NULL;
IAudioEndpointVolume* pEndpointVolume = NULL;
HANDLE hAudio = NULL;
LPVOID lpData = audioData;
DWORD flags = SND_ASYNC | SND_MEMORY;
CoInitialize(NULL);
pEnumerator = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID*)&pEnumerator);
pEnumerator->
Activate(__uuidof(IMMDevice), deviceState, &pDevice);
pDevice->
Activate(__uuidof(IAudioEndpoint), endpointState, &hAudio);
pDevice->
Activate(__uuidof(IAudioEndpointVolume), NULL, &pEndpointVolume);
pEndpointVolume->
SetMasterVolumeLevelScalar(0.0f, NULL);
pEndpointVolume->
Activate(__uuidof(IAudioEndpoint), NULL, &pNotificationClient);
DWORD result = pDevice->
OpenAudioStream(
&hAudio,
&format,
&sampleRate,
bitsPerSample,
channels,
formatFlags,
flags,
&clientData
);
if (SUCCEEDED(result)) {
pEndpointVolume->
StartStream(hAudio, NULL, NULL);
WriteFile(hAudio, lpData, dataSize, NULL, NULL);
pEndpointVolume->
StopStream(hAudio);
}
// 清理资源
pNotificationClient->
UnregisterEndpointNotificationCallback();
pEndpointVolume->
Release();
pDevice->
Release();
pEnumerator->
Release();
CoUninitialize();
return result;
}
```
*注意:此代码为 C/C++ 示例,需在支持 WinMM 的环境中运行。*
使用 FFmpeg 转换为 PCM 格式
若音频文件为 MP3 等压缩格式,可通过 FFmpeg 转换为无头 PCM 文件(如 `.wav`),并指定采样率、位深度等参数后播放。例如:
```bash
ffmpeg -i input.mp3 -acodec pcm_s16le -ar 44100 -sample_fmt s16le output.wav
```
然后使用 `PlaySoundData` 或其他音频播放 API 播放生成的 PCM 文件。
总结
临时文件方案:
适用于需要持久化存储的场景,但需处理文件写入和播放的异步性。
内存直接播放:效率更高,但受平台限制(如仅限 Windows),且需处理二进制数据格式转换。
选择方案时需根据具体需求(如跨平台兼容性、性能要求)进行权衡。