countdown/play_raw_audio.c

51 lines
1.1 KiB
C

#include "play_raw_audio.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <pulse/simple.h>
#include <pulse/error.h>
int play_raw_audio(char file_name[]) {
int pa_error = 0;
char content[1024] = "";
int myfd = open(file_name, O_RDONLY);
if (myfd == -1) {
perror("Failed to open audio file");
return 1;
}
pa_simple* simple = NULL;
pa_sample_spec ss;
ss.format = PA_SAMPLE_S16LE;
ss.rate = 48000;
ss.channels = 2;
// Temporarily redirect stderr to /dev/null
// because pulseaudio prints to stderr even though it does not set any error codes
FILE *original_stderr = stderr;
stderr = fopen("/dev/null", "w");
simple = pa_simple_new(NULL, "Audio Playback", PA_STREAM_PLAYBACK, NULL, "playback", &ss, NULL, NULL, &pa_error);
// Restore stderr
stderr = original_stderr;
int i = 0;
while (read(myfd, content, sizeof(content))) {
// skip the first 1024 bytes to not play the file header
if (i != 0) {
pa_simple_write(simple, content, sizeof(content), &pa_error);
}
i++;
}
pa_simple_drain(simple, NULL);
pa_simple_free(simple);
close(myfd);
return 0;
}