树莓派上的ALSA应用程序如何读取和播放WAV文件

9
尝试学习ALSA音频层,最终要为Raspberry Pi平台编写ALSA设备驱动程序。一开始,我从ALSA项目网站和其他在线资源中拼凑了各种样例来做最简单的事情:读取一个WAV文件并在默认声音设备上播放它。但是我无法让这个简单的C样例工作。
我使用libsndfile来进行所有的WAV文件读取/头解码。我验证了读入缓冲区的样本是正确的(对比程序读入的前400K个样本和将样本值转储到文本文件的sndfile-to-text应用程序)。所以我知道我的缓冲区包含正确的数据,问题必须在我传递给ALSA API的方式上。
运行时只在右声道产生声音,并且失真/模糊 - 几乎无法识别。顺便说一下,“aplay”应用程序完美地播放相同的WAV文件,并报告该文件为16位有符号LE、44100Hz、立体声,与我的应用程序报告的相匹配。在Raspberry Pi上运行此程序。
我将C程序精简到最小限度以节省空间,但我验证了所有API调用的正确返回代码。为什么这个简单的ALSA应用程序不能产生正确的声音?
#include <alsa/asoundlib.h>
#include <stdio.h>
#include <sndfile.h>

#define PCM_DEVICE "default"

int main(int argc, char **argv) {

    snd_pcm_t *pcm_handle;
    snd_pcm_hw_params_t *params;
    snd_pcm_uframes_t frames;
    int dir, pcmrc;

    char *infilename = "/home/pi/shortsample.wav";
    int* buf = NULL;
    int readcount;

    SF_INFO sfinfo;
    SNDFILE *infile = NULL;

    infile = sf_open(infilename, SFM_READ, &sfinfo);
    fprintf(stderr,"Channels: %d\n", sfinfo.channels);
    fprintf(stderr,"Sample rate: %d\n", sfinfo.samplerate);
    fprintf(stderr,"Sections: %d\n", sfinfo.sections);
    fprintf(stderr,"Format: %d\n", sfinfo.format);

    /* Open the PCM device in playback mode */
    snd_pcm_open(&pcm_handle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, 0);

    /* Allocate parameters object and fill it with default values*/
    snd_pcm_hw_params_alloca(&params);
    snd_pcm_hw_params_any(pcm_handle, params);
    /* Set parameters */
    snd_pcm_hw_params_set_access(pcm_handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
    snd_pcm_hw_params_set_format(pcm_handle, params, SND_PCM_FORMAT_S16_LE);
    snd_pcm_hw_params_set_channels(pcm_handle, params, sfinfo.channels);
    snd_pcm_hw_params_set_rate(pcm_handle, params, sfinfo.samplerate, 0);

    /* Write parameters */
    snd_pcm_hw_params(pcm_handle, params);

    /* Allocate buffer to hold single period */
    snd_pcm_hw_params_get_period_size(params, &frames, &dir);
    fprintf(stderr,"# frames in a period: %d\n", frames);

    fprintf(stderr,"Starting read/write loop\n");
    buf = malloc(frames * sfinfo.channels * sizeof(int));
    while ((readcount = sf_readf_int(infile, buf, frames))>0) {

        pcmrc = snd_pcm_writei(pcm_handle, buf, readcount);
        if (pcmrc == -EPIPE) {
            fprintf(stderr, "Underrun!\n");
            snd_pcm_prepare(pcm_handle);
        }
        else if (pcmrc < 0) {
            fprintf(stderr, "Error writing to PCM device: %s\n", snd_strerror(pcmrc));
        }
        else if (pcmrc != readcount) {
            fprintf(stderr,"PCM write difffers from PCM read.\n");
        }

    }
    fprintf(stderr,"End read/write loop\n");

    snd_pcm_drain(pcm_handle);
    snd_pcm_close(pcm_handle);
    free(buf);

    return 0;
}
1个回答

4

您必须检查所有可能失败的snd_函数的返回值。

S16_LE格式每个采样有两个字节,但int有四个字节。请使用short代替,并使用sf_readf_short


我的真实代码确实检查了所有的返回值,我只是为了发布的目的而缩短了它。将 int 改为 short 修复了问题,现在 WAV 正确播放了...谢谢! - Mark McMillan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接