嘿嘿,
所以我正在尝试用 libao 播放 pcm 音频。我的目标是让播放可以暂停和取消。
出于某种原因,alsa 驱动程序的输出断断续续,播放速度非常非常快。就像您正在擦洗输出一样。如果我只是播放整个缓冲区,它就可以正常工作。
这是播放循环:
uint_32 next_read = 8192;
while (1) {
ao_play(device, (char *) buffer, next_read);
buffer += next_read;
if (cancel_playback) {
printf("Cancel\n");
break;
}
}
这是准备缓冲区的代码。我正在将整个流加载到内存中:
ao_device *device;
ao_sample_format format;
SF_INFO sfinfo;
int default_driver;
short *buffer;
uint_32 buf_size;
signal(SIGINT, on_cancel_playback);
SNDFILE *file = sf_open("test.wav", SFM_READ, &sfinfo);
printf("Samples: %d\n", sfinfo.frames);
printf("Sample rate: %d\n", sfinfo.samplerate);
printf("Channels: %d\n", sfinfo.channels);
ao_initialize();
default_driver = ao_default_driver_id();
switch (sfinfo.format & SF_FORMAT_SUBMASK) {
case SF_FORMAT_PCM_16:
format.bits = 16;
break;
case SF_FORMAT_PCM_24:
format.bits = 24;
break;
case SF_FORMAT_PCM_32:
format.bits = 32;
break;
case SF_FORMAT_PCM_S8:
format.bits = 8;
break;
case SF_FORMAT_PCM_U8:
format.bits = 8;
break;
default:
format.bits = 16;
break;
}
format.channels = sfinfo.channels;
format.rate = sfinfo.samplerate;
format.byte_format = AO_FMT_NATIVE;
format.matrix = 0;
device = ao_open_live(default_driver, &format, NULL);
if (device == NULL) {
fprintf(stderr, "Error opening device.\n");
return 1;
}
buf_size = (uint_32) (format.channels * sfinfo.frames * sizeof(short));
buffer = calloc(buf_size, sizeof(char));
printf("buffer-size: %d\n", buf_size);
printf("Loading file into buffer...\n");
sf_readf_short(file, buffer, buf_size);
printf("Closing file...\n");
sf_close(file);
printf("Playback...\n");
找到我自己的答案:D
short *buffer;
->
char *buffer;
问题是我想跳过这一行中的 next_read 个字节:
buffer += next_read;
但是类型很短 * 所以我跳过了 2 个字节而不是一个。 :/
我是一名优秀的程序员,十分优秀!