该回答引用GPTᴼᴾᴱᴺᴬᴵ
使用 miniaudio 库播放音频的基本流程如下:
- 初始化一个 ma_engine 实例。
- 调用 ma_engine_play_sound 函数播放音频文件。
- 等待音频播放结束或者用户中止播放。
- 调用 ma_engine_uninit 函数释放 ma_engine 实例。
针对你的问题,可能是你需要使用合适的解码器来解码 MP3 文件。miniaudio 库自身并不包含解码器,需要依赖其他库来完成解码工作。比如可以使用 minimp3 库,或者 libmpg123 库等。在使用 miniaudio 的时候,你需要提前把音频数据解码成 PCM 格式,并将 PCM 数据传给 miniaudio 库进行播放。
你可以参考一下下面这个示例代码,使用 minimp3 库对 MP3 文件进行解码,然后将解码后的 PCM 数据传给 miniaudio 库进行播放:
#define MINIAUDIO_IMPLEMENTATION
#include "../miniaudio.h"
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
ma_result result;
ma_engine engine;
ma_decoder decoder;
if (argc < 2) {
printf("No input file.");
return -1;
}
result = ma_engine_init(NULL, &engine);
if (result != MA_SUCCESS) {
printf("Failed to initialize audio engine.");
return -1;
}
result = ma_decoder_init_file(argv[1], NULL, &decoder);
if (result != MA_SUCCESS) {
printf("Failed to open input file.");
ma_engine_uninit(&engine);
return -1;
}
ma_uint64 frameCount = ma_decoder_get_length_in_pcm_frames(&decoder);
ma_sound_group soundGroup;
result = ma_sound_group_init(&engine, 2, ma_format_f32, ma_decoder_get_output_sample_rate(&decoder), frameCount, &soundGroup);
if (result != MA_SUCCESS) {
printf("Failed to create sound group.");
ma_decoder_uninit(&decoder);
ma_engine_uninit(&engine);
return -1;
}
ma_uint32 decodedFrameCount;
float* pFrames = (float*)malloc(ma_sound_group_get_bytes_per_frame(&soundGroup) * frameCount);
if (pFrames == NULL) {
printf("Failed to allocate memory for decoded PCM frames.");
ma_sound_group_uninit(&soundGroup);
ma_decoder_uninit(&decoder);
ma_engine_uninit(&engine);
return -1;
}
result = ma_decoder_read_pcm_frames(&decoder, pFrames, frameCount, &decodedFrameCount);
if (result != MA_SUCCESS) {
printf("Failed to read PCM frames from input file.");
free(pFrames);
ma_sound_group_uninit(&soundGroup);
ma_decoder_uninit(&decoder);
ma_engine_uninit(&engine);
return -1;
}
result = ma_sound_group_add_sound(&soundGroup, pFrames, decodedFrameCount);
if (result != MA_SUCCESS) {
printf("Failed to add sound to group.");
free(pFrames);
ma_sound_group_uninit(&soundGroup);
ma_decoder_uninit(&decoder);
ma_engine_uninit(&engine);
return -1;
}
free(pFrames);
ma_decoder_uninit(&decoder);
result = ma_sound_group_play(&soundGroup);
if (result != MA_SUCCESS) {
printf("Failed to play sound group.");
ma_sound_group_uninit(&soundGroup);
ma_engine_uninit(&engine);
return -1;
}
printf("Playing \"%s\"...\n", argv[1]);
printf("Press Enter to quit...");
getchar();
ma_sound_group_uninit(&soundGroup);
ma_engine_uninit(&engine);
return 0;