How can I use the asound library in C to play a WAV file using the default pcm device?
Assistant
User
Can you go into more detail about how you calculated the buff_size variable? Would this change if instead we had 1 channel instead?
Assistant
User
Is the function snd_pcm_writei responsible for writing to the buffer of the audio device only? Or does snd_pcm_drain actually cause the audio to start playing? Or am I completely wrong here?
Assistant
User
Are theses functions blocking? What if I instead wanted to use non blocking method instead?
Assistant
User
I noticed you check for -EPIPE in the while loop. When would snd_pcm_writei return this, and why are you calling snd_pcm_prepare in response to that?
Assistant
To play a WAV file using the ALSA (Advanced Linux Sound Architecture) library in C, you'll need to use a few key functions from the ALSA library to set up PCM (Pulse Code Modulation) device parameters, read audio data from a WAV file, and write it to the PCM device for playback. Below is a step-by-step guide with example code segments, showing how to accomplish this.
Prerequisites
You need to have the ALSA library installed on your Linux system. Typically, you can install it using a package manager:
bash
sudo apt-get install libasound2-dev # For Debian/Ubuntu
Your C development environment should be set up and ready.
Steps to Play a WAV File
Include Necessary Headers: You'll need the ALSA header and standard I/O headers.
c
#include <alsa/asoundlib.h>
#include <stdio.h>
Open PCM Device: You must open a PCM device before you can send any sound data to it.
Set PCM Parameters: Set the PCM hardware parameters like sample rate, channels, and format.
Configure WAV File Reading: Properly set up reading the WAV file, extracting its format, sample rate, and data.
Write Audio Frames to PCM Device: Read frames from the WAV file and write them to the PCM device.
Example Code
Here is an example code to demonstrate the entire process:
c
#include <stdio.h>
#include <alsa/asoundlib.h>
#define PCM_DEVICE "default"
int main(int argc, char *argv[]) {
unsigned int pcm, tmp, dir;
snd_pcm_t *pcm_handle;
snd_pcm_hw_params_t *params;
snd_pcm_uframes_t frames;
char *buff;
int buff_size, loops;
FILE *fp;
int rate, channels, seconds;
int size;
// Open the PCM device in playback mode
if (pcm = snd_pcm_open(&pcm_handle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, 0) < 0) {
printf("ERROR: Can't open \"%s\" PCM device. %s\n", PCM_DEVICE, snd_strerror(pcm));
return -1;
}
// Allocate parameters object and fill it with default values
snd_pcm_hw_params_alloca(¶ms);
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, 2); // Stereo
rate = 44100; // Audio CD quality
snd_pcm_hw_params_set_rate_near(pcm_handle, params, &rate, 0);
// Write parameters
if (pcm = snd_pcm_hw_params(pcm_handle, params) < 0) {
printf("ERROR: Cannot set hardware parameters. %s\n", snd_strerror(pcm));
return -1;
}
// Prepare interface
snd_pcm_prepare(pcm_handle);
// Calculate buffer size (4 bytes/frame, 2 bytes/sample, 2 channels)
snd_pcm_hw_params_get_buffer_size(params, &size);
buff_size = size * 4;
buff = (char *) malloc(buff_size);
// WAV file operations
fp = fopen("file.wav", "rb");
if (fp == NULL) {
fprintf(stderr, "cannot open file\n");
return -1;
}
// Skip WAV header (you should normally read it to extract audio details)
fseek(fp, 44, SEEK_SET); // Assuming header is 44 bytes long
// Write PCM data to the device
while ((tmp = fread(buff, 1, buff_size, fp)) > 0) {
if (pcm = snd_pcm_writei(pcm_handle, buff, tmp / 4) == -EPIPE) {
printf("XRUN.\n");
snd_pcm_prepare(pcm_handle);
} else if (pcm < 0) {
printf("ERROR. Can't write to PCM device. %s\n", snd_strerror(pcm));
}
}
// Close the PCM device and free allocated memory
snd_pcm_drain(pcm_handle);
snd_pcm_close(pcm_handle);
free(buff);
fclose(fp);
return 0;
}
Explanation
This program opens the default PCM device for playback, sets up the hardware parameters for the audio stream, and plays audio from a WAV file named "file.wav". Make sure to replace "file.wav" with the path of your specific WAV file.
It assumes a sample format of 16-bit little-endian, stereo, 44.1 kHz, which is common for WAV files but should be checked and adjusted according to the specific file you are using.
The WAV header is skipped; in a full application, you should read the header to validate that the format is correct.
Caveats
Error handling is somewhat basic in this example; you may need to expand it based on your specific requirements.
This code doesn't handle the potential variability in WAV file formats. You may need more robust parsing depending on the source of your WAV files.
By following these guidelines and using this example as a basis, you can expand and adapt it for your particular needs in audio playback with the ALSA library in C.
Certainly! Let’s delve a bit deeper into how the buff_size variable is calculated and how it would change with different audio configurations, such as when using a single channel instead.
Buffer Size Calculation
The buffer size calculation depends on several factors: the number of frames in the buffer, the number of channels, and the sample size (sample format). In the given example:
snd_pcm_hw_params_get_buffer_size: This function retrieves the size of the buffer in frames. A frame in ALSA terminology encompasses one sample per channel.
Sample Size: For SND_PCM_FORMAT_S16_LE, each sample is 16 bits (2 bytes). This format represents 'Signed 16-bit Little Endian'.
Channels: The number of channels refers to whether the audio is mono (1 channel) or stereo (2 channels), or more for surround sound systems.
Given the settings:
Stereo Output: 2 channels
Sample Format: SND_PCM_FORMAT_S16_LE (2 bytes per sample)
The formula used for calculating buff_size was: size * 4. Here,
size obtained from snd_pcm_hw_params_get_buffer_size is the number of frames.
Since each frame for stereo format has 2 samples and each sample takes 2 bytes, each frame occupies 2 channels * 2 bytes = 4 bytes.
So, effectively, buff_size in bytes for stereo 16-bit audio is number of frames * 4 bytes/frame.
How Would This Change for Mono (1 Channel)?
If the configuration is changed to mono (1 channel), each frame would then contain only 1 sample (since a frame includes one sample per channel). The calculation would thus be:
Sample Format: Still SND_PCM_FORMAT_S16_LE (2 bytes per sample)
Channels: 1 (Mono)
Each frame would then occupy 1 channel * 2 bytes = 2 bytes per frame. So, if size is still the number of frames, then buff_size would be size * 2.
Adjusting Code for Mono Audio
To configure the ALSA settings for 1 channel, you need to modify the channel setting in the hardware parameters:
And adjust the buff_size to account for the mono configuration:
c
buff_size = size * 2; // Since each frame now has only 1 sample of 2 bytes
Here's how a small section of the setup might look:
c
// Set PCM parameters for 1 channel (Mono)
snd_pcm_hw_params_set_channels(pcm_handle, params, 1);
snd_pcm_hw_params_set_rate_near(pcm_handle, params, &rate, 0);
// Calculation of buffer size when using 1 channel
snd_pcm_hw_params_get_buffer_size(params, &size);
buff_size = size * 2; // 2 bytes per frame in mono
Conclusion
The buff_size calculation directly depends on the audio configuration used, specifically the sample size and the number of channels. Changing from stereo to mono, as illustrated, reduces the buffer size per frame, which is crucial for setting the correct buffer size during audio data management in applications.
You've highlighted an important aspect of audio playback with ALSA. Let's clarify the roles of snd_pcm_writei and snd_pcm_drain in the ALSA playback process, as well as how audio playback is managed with these functions.
Function snd_pcm_writei
The function snd_pcm_writei is responsible for writing interleaved samples to the playback buffer of the audio device. Here, "interleaved" means that if you have multiple channels (like stereo), the samples are laid out in the buffer as L1, R1, L2, R2, ..., where L and R represent left and right channel samples, respectively.
When you write data using snd_pcm_writei, it copies data from your application buffer into the ALSA buffer, which is maintained by the ALSA system. This copy does not necessarily start the playback instantly. Playback usually starts when there's enough data in the ALSA buffer to ensure smooth audio output, or you have explicitly asked ALSA to start playing the data.
Function snd_pcm_drain
snd_pcm_drain is used at the end of playback. What it does is wait for all the frames in the buffer to be played (i.e., it waits for the buffer to be "drained"). It ensures that all the audio data that has been written to the PCM device is played before the device is stopped. This is particularly useful when you are playing a fixed set of data and want to make sure that the playback completes before you close the device or terminate your application.
How Playback Actually Starts
Buffer Threshold and Start Threshold: ALSA playback usually starts automatically when the buffer reaches a certain level known as the "start threshold." This ensures that playing starts only when there's enough data in the buffer to provide continuous sound without underruns. You can adjust this threshold using ALSA settings, but by default, it's managed internally to begin playback when enough data is provided.
Explicit Start: If for some reason automatic starting based on the threshold doesn't fit your needs, ALSA also provides a function snd_pcm_start, which explicitly starts playback even if the start threshold hasn't been reached.
Example Flow in an Application
Given these functions, a typical flow of a playback application would be:
Open and set up the PCM device.
Write data continuously using snd_pcm_writei (handling underruns if they occur by checking for -EPIPE and then preparing the device again with snd_pcm_prepare).
When all data has been written, use snd_pcm_drain to wait for all remaining data to be played out.
Close the device.
Summary
So, summarizing the roles:
snd_pcm_writei: Writes audio data to the ALSA system buffer (not directly to hardware). Playback might start as a result of this call if the start threshold is reached.
snd_pcm_drain: Ensures that all data in the buffer is played out (i.e., waits for the buffer to empty) before returning, useful at the end of playback.
Thus, ALSA manages playback through a combination of buffering strategies, automatic and manual start controls, and synchronization techniques to ensure smooth operation in audio applications.
Blocking vs. Non-blocking in ALSA
In ALSA (Advanced Linux Sound Architecture), functions like snd_pcm_writei and snd_pcm_drain are indeed blocking by default. Here's what that means in practical terms:
snd_pcm_writei: This function is blocking. It writes the provided frames to the PCM (Pulse Code Modulation) device and only returns once all the frames have either been written or an error occurs. If the internal buffer of the PCM device does not have enough space to hold all the data you're trying to write, this function will block (wait) until there is enough space.
snd_pcm_drain: This function is also blocking. It waits for all the frames in the buffer to be played by the audio hardware before it returns. This ensures that all written data is actually played out before the function completes.
Using Non-blocking Mode
If you prefer not to block your main application thread while performing audio operations, you can set up your PCM device in non-blocking mode using snd_pcm_open. Here is how you would initialize this:
c
snd_pcm_t *pcm_handle;
int rc = snd_pcm_open(&pcm_handle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
if (rc < 0) {
fprintf(stderr, "unable to open pcm device: %s\n", snd_strerror(rc));
return -1;
}
In non-blocking mode, functions like snd_pcm_writei will return immediately if they cannot process all the given frames. It mainly returns -EAGAIN if the operation would block (e.g., the buffer is full). You must handle this case appropriately, possibly by retrying the write after a delay or performing other tasks before retrying.
Non-blocking Example
In a non-blocking scenario using snd_pcm_writei, you could use a loop to handle -EAGAIN errors like this:
c
int frames_written;
while ((frames_written = snd_pcm_writei(pcm_handle, buffer, frames)) < 0) {
if (frames_written == -EAGAIN) {
// Perform other tasks, or sleep briefly
usleep(1000); // Sleep for 1ms
continue;
} else if (frames_written == -EPIPE) {
fprintf(stderr, "XRUN.\n");
snd_pcm_prepare(pcm_handle);
} else {
fprintf(stderr, "Error writing to PCM device: %s\n", snd_strerror(frames_written));
break;
}
}
Challenges and Considerations
Polling vs. Event-Driven: In non-blocking mode, you're effectively either polling for buffer space or would need to use another method like poll() system calls to wait for the buffer to have enough space. This can complicate the program design.
CPU Usage: Non-blocking mode might increase CPU usage if not handled carefully (e.g., continuously polling in a tight loop without delay).
Complexity: Error handling (like dealing with underruns) and managing state can become more complex in non-blocking modes.
Conclusion
Using non-blocking ALSA mode is beneficial when you need to perform other computational tasks concurrently in the same thread and cannot afford to have the thread blocked by audio operations. It requires careful design consideration to handle polling and waiting strategies efficiently, and to avoid high CPU usage from excessive busy-waiting.
The handling of -EPIPE when using ALSA's snd_pcm_writei function is crucial for managing what are termed "underruns" in audio processing. An underrun occurs when the audio buffer that the DAC (Digital-to-Analog Converter) reads from becomes empty before it has been refilled with new data. This situation is likely to happen when the application fails to supply enough data in time to keep up with the playback rate. Here's a closer look at these aspects:
When snd_pcm_writei Returns -EPIPE
The snd_pcm_writei function returns -EPIPE when an underrun occurs. In ALSA, an underrun is treated as an error condition, signaling that the audio hardware was ready to play more sound data, but the buffer was empty.
Reasons for an Underrun
High System Load: Other processes are using too much CPU time.
Inefficient Application Processing: Your application might be taking too long to process or fetch the data to be played.
Too Small Buffer Sizes: Very small buffer sizes can be more susceptible to underruns, as the buffer can empty more quickly, and frequent data feeds are required.
Response with snd_pcm_prepare
When -EPIPE is encountered, it indicates that the buffer underflow has disrupted your PCM stream, putting it into an erroneous state (SND_PCM_STATE_XRUN). Before you can resume normal operations (and to clear the error), you must prepare the stream to be restarted. This is done using the snd_pcm_prepare() function.
Steps with snd_pcm_prepare
c
if (frames_written == -EPIPE) {
fprintf(stderr, "XRUN.\n");
snd_pcm_prepare(pcm_handle);
}
Executing snd_pcm_prepare() after an underrun:
Resets the PCM stream: This clears the XRUN state and prepares it to start running again when data is written next.
Opens a path to resumption of data writing: After calling snd_pcm_prepare(), you can continue to push data to the buffer with snd_pcm_writei.
Continuous Writing Example
In practical applications, especially in non-blocking mode or in real-time streaming scenarios, your code should be capable of continuously dealing with potential underruns by preparing the stream and retrying the write operation:
Handling -EPIPE and correctly managing the PCM device state are essential tasks for robust audio application development using ALSA. Proper management ensures smooth playback without interruptions or glitches caused by device errors like underruns. Additionally, tuning other parameters such as buffer size and period size can help mitigate the chances of encountering these errors.