@wayne.swaniawski
To play .wav files in C++ on Linux, you can use the ALSA (Advanced Linux Sound Architecture) library. Here is an example code that demonstrates how to play a .wav file:
- Start by including the necessary headers:
1
2
3
|
#include <alsa/asoundlib.h>
#include <iostream>
#include <string>
|
- Define the name of the .wav file you want to play:
1
|
const std::string filename = "your_file.wav";
|
- Create a function to handle errors:
1
2
3
4
5
|
void handleError(const std::string& errorMessage, snd_pcm_t* pcm) {
std::cerr << errorMessage << ": " << snd_strerror(snd_pcm_prepare(pcm)) << std::endl;
snd_pcm_close(pcm);
exit(EXIT_FAILURE);
}
|
- Initialize the ALSA PCM device:
1
2
3
4
|
snd_pcm_t* pcm;
if (snd_pcm_open(&pcm, "default", SND_PCM_STREAM_PLAYBACK, 0) < 0) {
handleError("Error opening PCM device", pcm);
}
|
- Set the desired PCM parameters:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
snd_pcm_hw_params_t* hw_params;
if (snd_pcm_hw_params_malloc(&hw_params) < 0) {
handleError("Error allocating hardware parameters", pcm);
}
if (snd_pcm_hw_params_any(pcm, hw_params) < 0) {
handleError("Error initializing hardware parameters", pcm);
}
if (snd_pcm_hw_params_set_access(pcm, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED) < 0) {
handleError("Error setting access type", pcm);
}
if (snd_pcm_hw_params_set_format(pcm, hw_params, SND_PCM_FORMAT_S16_LE) < 0) {
handleError("Error setting sample format", pcm);
}
unsigned int sampleRate = 44100;
if (snd_pcm_hw_params_set_rate_near(pcm, hw_params, &sampleRate, 0) < 0) {
handleError("Error setting sample rate", pcm);
}
|
- Apply the hardware parameters to the PCM device:
1
2
3
4
|
if (snd_pcm_hw_params(pcm, hw_params) < 0) {
handleError("Error setting parameters", pcm);
}
snd_pcm_hw_params_free(hw_params);
|
- Prepare the PCM device for playback:
1
2
3
|
if (snd_pcm_prepare(pcm) < 0) {
handleError("Error preparing PCM device", pcm);
}
|
- Open the .wav file for reading:
1
2
3
4
|
FILE* file = fopen(filename.c_str(), "rb");
if (!file) {
handleError("Error opening file", pcm);
}
|
- Read and play the file data:
1
2
3
4
5
6
7
8
|
constexpr int bufferSize = 128;
char buffer[bufferSize];
while (fread(buffer, sizeof(char), bufferSize, file) == bufferSize) {
if (snd_pcm_writei(pcm, buffer, bufferSize / 2) < 0) {
handleError("Error writing to PCM device", pcm);
}
}
|
- Close the file and the PCM device:
1
2
|
fclose(file);
snd_pcm_close(pcm);
|
That's it! You can now run your program and it will play the .wav file through your Linux audio system. Make sure you link your executable with the ALSA library by adding -lasound
to your compiler command.