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

查看:50
本文介绍了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 没有意义(这与 snd_pcm_writei() 完全相同已经做了).只有在动态生成样本并且可以将它们直接写入设备的缓冲区时,才能减少延迟.

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天全站免登陆