Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Terminal radio player
#include <ncurses.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
typedef struct station {
char name[256];
char url[256];
} station;
station stations[256];
int stationCount;
int player = 0;
int devnull;
void load_stations() {
FILE *stationsFile = fopen("stations.txt", "r");
stationCount = 0;
char line[2048];
while (fgets(line, 2048, stationsFile)) {
int seperatorPos = strchr(line, '|')-line;
strncpy(stations[stationCount].name, line, seperatorPos);
strncpy(stations[stationCount].url, line+seperatorPos+1, strlen(line)-seperatorPos-2);
stationCount++;
}
}
void play_url(char *url) {
if (player != 0) {
kill(player, SIGTERM);
}
signal(SIGCHLD, SIG_IGN);
player = fork();
if (player == 0) {
// Child process
dup2(devnull, 1);
dup2(devnull, 2);
execl("/usr/bin/mplayer", "mplayer", url);
}
}
int main() {
initscr();
noecho();
cbreak();
keypad(stdscr, TRUE);
curs_set(FALSE);
start_color();
init_pair(1, COLOR_WHITE, COLOR_BLACK);
init_pair(2, COLOR_CYAN, COLOR_BLACK);
devnull = open("/dev/null", O_RDONLY);
load_stations();
int key = 0;
int selectedStation = 0;
while (1) {
if (key == KEY_DOWN) {
selectedStation++;
selectedStation = selectedStation % stationCount;
}else if (key == KEY_UP) {
selectedStation--;
if (selectedStation < 0) {
selectedStation = stationCount-1;
}
}else if (key == KEY_RIGHT || key == '\n') {
play_url(stations[selectedStation].url);
}else if (key == 's') {
if (player != 0) {
kill(player, SIGTERM);
player = 0;
}
}else if (key == 'q') {
if (player != 0) {
kill(player, SIGTERM);
}
endwin();
return 0;
}
clear();
for (int i=0;i<stationCount;i++) {
move(i, 2);
if (i == selectedStation) {
attrset(COLOR_PAIR(2));
printw("---> ");
}else {
attrset(COLOR_PAIR(1));
printw(" ");
}
printw("%d. %s", i+1, stations[i].name);
}
attrset(COLOR_PAIR(1));
printw("\n\n");
printw("Terminal Radio\n");
printw("Up-Down > Select Station | Enter > Play selected station | q > Quit | s > Stop");
key = getch();
}
endwin();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.