countdown/play_raw_audio.c

51 lines
1.1 KiB
C
Raw Normal View History

2023-08-16 22:38:32 +02:00
#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;
2023-08-16 22:51:00 +02:00
char content[1024] = "";
2023-08-16 22:38:32 +02:00
2023-08-16 22:51:00 +02:00
int myfd = open(file_name, O_RDONLY);
2023-08-16 22:38:32 +02:00
if (myfd == -1) {
perror("Failed to open audio file");
return 1;
}
2023-08-16 22:52:50 +02:00
pa_simple* simple = NULL;
pa_sample_spec ss;
ss.format = PA_SAMPLE_S16LE;
ss.rate = 48000;
ss.channels = 2;
2023-08-16 22:38:32 +02:00
2023-08-16 22:52:50 +02:00
// Temporarily redirect stderr to /dev/null
2023-08-16 22:38:32 +02:00
// because pulseaudio prints to stderr even though it does not set any error codes
FILE *original_stderr = stderr;
stderr = fopen("/dev/null", "w");
2023-08-16 22:51:00 +02:00
simple = pa_simple_new(NULL, "Audio Playback", PA_STREAM_PLAYBACK, NULL, "playback", &ss, NULL, NULL, &pa_error);
2023-08-16 22:38:32 +02:00
// Restore stderr
stderr = original_stderr;
2023-08-16 22:52:50 +02:00
int i = 0;
2023-08-16 22:51:00 +02:00
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++;
}
2023-08-16 22:38:32 +02:00
2023-08-16 22:51:00 +02:00
pa_simple_drain(simple, NULL);
2023-08-16 22:38:32 +02:00
2023-08-16 22:51:00 +02:00
pa_simple_free(simple);
2023-08-16 22:38:32 +02:00
2023-08-16 22:51:00 +02:00
close(myfd);
2023-08-16 22:38:32 +02:00
2023-08-16 22:51:00 +02:00
return 0;
2023-08-16 22:38:32 +02:00
}