c语言简易音乐播放器
时间: 2023-12-02 15:41:33 浏览: 49
这是一个使用C语言编写的简易音乐播放器,主要实现了歌词与歌曲之间的同步。具体实现原理是将歌词切割并存入数组中,通过sleep函数创建虚拟时钟与歌词中的时间相对应。然后创建一个进程调用mplayer播放歌曲,同时开始计时就可以完成歌词与歌曲之间的同步。以下是主要代码:
1. my_lrc_play.h
```c
#ifndef MY_LRC_PLAY_H
#define MY_LRC_PLAY_H
void my_lrc_play();
#endif
```
2. my_lrc_play.c
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "my_lrc_play.h"
#define MAX_LRC_LINE 1024
#define MAX_LRC_SIZE 1024
typedef struct lrc_node {
int time;
char lrc[MAX_LRC_SIZE];
struct lrc_node *next;
} LrcNode;
LrcNode *head = NULL;
void *lrc_thread(void *arg) {
int time = 0;
LrcNode *p = head;
while (p != NULL) {
if (time == p->time) {
printf("%s\n", p->lrc);
p = p->next;
}
sleep(1);
time++;
}
return NULL;
}
void my_lrc_play() {
FILE *fp = fopen("test.lrc", "r");
if (fp == NULL) {
printf("Open file failed!\n");
return;
}
char buf[MAX_LRC_LINE];
while (fgets(buf, MAX_LRC_LINE, fp) != NULL) {
int len = strlen(buf);
if (len <= 10) {
continue;
}
LrcNode *node = (LrcNode *) malloc(sizeof(LrcNode)); node->time = (buf[1] - '0') * 600 + (buf[2] - '0') * 60 + (buf[4] - '0') * 10 + (buf[5] - '0');
strcpy(node->lrc, buf + 10);
node->next = NULL;
if (head == NULL) {
head = node;
} else {
LrcNode *p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
}
pthread_t tid;
pthread_create(&tid, NULL, lrc_thread, NULL);
char *song_path = "test.mp3";
pid_t pid;
pid = fork();
if (pid < 0) {
perror("fork");
} else if (pid == 0) {
close(1);
close(2);
execlp("mplayer", "mplayer", "-slave", "-quiet", song_path, NULL);
exit(0);
} else;
wait(NULL);
}
```