libao:播放音频块作为序列口吃

时间:2015-03-22 15:18:08

标签: c audio alsa pcm libsndfile

Heyho,

所以我正在尝试用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");

1 个答案:

答案 0 :(得分:1)

找到我自己的答案:D

short *buffer; 

- >

char *buffer;

问题是我想在此行中跳过 next_read 字节:

buffer += next_read;

但是类型很短*因此我跳过2个字节的instread。 :/