Alsa API:如何在C中使用mmap? [英] Alsa api: how to use mmap in c?

查看:466
本文介绍了Alsa API:如何在C中使用mmap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用snd_pcm_writei播放声音文件,该声音文件先前已装入短数组(16位PCM格式).为了播放此声音,我创建了一个缓冲区(short *),其中包含一个句点(或片段).然后,我使用一个while循环来调用snd_pcm_writei,这给了我这一行:

I'm currently using snd_pcm_writei to play a sound file that was previously loaded into an array of short (16 bits PCM format). To play this sound I create a buffer (short*), that contains a period (or fragment). Then, I use a while loop to call snd_pcm_writei which gives me that line:

int err = snd_pcm_writei(handle, buffer, frames);

了解它的工作原理非常简单,并且一切正常,我可以听到声音.但是,我想尝试使用mmap代替writei,但是我并没有真正理解它. 我正面临缺乏文档和清晰示例的问题. 谁能解释mmap如何与alsa一起使用,以及如何将我的代码转换为使用mmap的东西?基本上,我仍然想使用缓冲区播放数组中的内容(因此,数组的大小为一个周期).谢谢.

It is pretty simple to understand how it works, and everything works fine, I can hear the sound. However, I'd like to try to use mmap instead of writei, but I don't really get it. I'm facing the lack of documentation and clear examples. Can anyone explain how mmap works with alsa, and how to convert my code to something that uses mmap? Basically, I'd still like to play what's in my array, using the buffer (so an array of short that has a size of one period). Thanks.

推荐答案

首先,您需要设置一种MMAP类型的访问类型(通常是SND_PCM_ACCESS_MMAP_INTERLEAVED而不是SND_PCM_ACCESS_RW_INTERLEAVED).

First you need to set the access type one of the MMAP types (typically, SND_PCM_ACCESS_MMAP_INTERLEAVED instead of SND_PCM_ACCESS_RW_INTERLEAVED).

要写入缓冲区时,请使用要写入的帧数调用snd_pcm_mmap_begin().如果此函数成功执行,它将返回一个指向缓冲区的指针(areas[0].addr,或用于非交错或复杂访问类型的多个指针),该缓冲区的偏移量(offset)以及实际可以写入多少帧.

When you want to write to the buffer, call snd_pcm_mmap_begin() with the number of frames you want to write. If this function succeeds, it returns a pointer to the buffer (areas[0].addr, or multiple pointers for non-interleaved or complex access types), an offset into the buffer (offset), and how many frames you actually can write.

写完样本后,用您已写出的实际帧数调用snd_pcm_mmap_commit().

After writing the samples, call snd_pcm_mmap_commit() with the actual number of frames you have written.

请注意,将样本从您自己的缓冲区复制到设备的缓冲区中时,使用mmap没有意义(与完全相同). 仅在动态生成样本并将其直接写入设备的缓冲区时,才可以减少延迟.

Please note that using mmap does not make sense when you are copying the sample from your own buffer into the device's buffer (this is exactly the same what snd_pcm_writei() already does). You can reduce latency only if you are generating the samples on the fly and can write them directly to the device's buffer.

这篇关于Alsa API:如何在C中使用mmap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆