main.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"fun.h"
int main(int argc,char argv[])
{
char *file_date=NULL;//存歌词数据
char *buf[128]={NULL}; //存分割后的歌词
int i=0; //记录歌词行数
int n=0;
LRC *head=NULL; //链表头
file_date=read_file("简单爱.lrc");//读取歌词数据
printf("%s",file_date); //测试是否读到
//切割歌词
buf[i] = strtok(file_date,"\r\n");
while(buf[i] !=NULL)
{
i++;
buf[i]=strtok(NULL,"\r\n");
}
n=i;
//遍历分割后的歌词
i=0;
while(buf[i] != NULL)
{
printf("%s\n",buf[i]);
i++;
}
//分析前四行
for(i=0;i<4;i++)
{
char tmp[128]="";
sscanf(buf[i],"%*[^:]:%[^]]",tmp);
printf("%s\n",tmp);//测试是否提取成功
}
for(i=4;i<n;i++)
{
//歌词的位置
char *str_lrc = buf[i];
while(*str_lrc =='[')
{
str_lrc+=10;
}
char *str_time = buf[i];
while(*str_time == '[')
{
int m = 0;
int s = 0;
int time = 0;
sscanf(str_time,"[%d:%d.41]", &m,&s);
time = m*60+s;
LRC tmp;
tmp.time = time;
strcpy(tmp.lrc,str_lrc);
head = insert_link(head,tmp);//插入链表
str_time += 10;
}
}
/*mplayer_play("简单爱.mp3");*/
int j = 0;
while(1)
{
printf("\r%02d:%02d",j/60,j%60);
fflush(stdout);
LRC *ret = search_link(head,j);
if(ret != NULL)
{
printf("%s\n",ret->lrc);
}
sleep(1);
j++;
}
return 0;
}
fun.c
#include<stdio.h>
#include<stdlib.h>
#include"fun.h"
char* read_file(char *name) //读取歌词
{
char *data=NULL;
long file_length = 0;
FILE *fp=NULL;
fp = fopen(name ,"r");
if(fp==NULL)
{
perror("fopen");
return NULL;
}
fseek(fp,0,2);
file_length=ftell(fp);
rewind(fp);
data=(char*)calloc(1,file_length);
if (data==NULL)
{
perror("calloc");
return NULL;
}
fread(data,file_length,1,fp);
fclose(fp);
return data;
}
LRC* insert_link(LRC *head,LRC tmp)//链表插入
{
LRC *pi =(LRC *)calloc(1,sizeof(LRC));
if(pi==NULL)
{
perror("calloc");
return head;
}
*pi = tmp;
pi->next=NULL;
if(head==NULL)
{
head=pi;
return head;
}
else
{
LRC *pb=head,*pf=head;
while(pb->time<pi->time &&pb->next!=NULL)
{
pf = pb;
pb = pb->next;
}
if(pb->time>=pi->time)
{
if(pb==head)
{
pi->next=head;
head=pi;
return head;
}
else
{
pf->next=pi;
pi->next=pb;
return head;
}
}
else
{
pb->next=pi;
return head;
}
}
return head;
}
void print_link(LRC *head)
{
if(head==NULL)
{
printf("link not find");
return;
}
else
{
LRC *pb=head;
do
{
printf("time =%d,lrc=%s\n",pb->time,pb->lrc);
pb=pb->next;
}while(pb!=NULL);
}
return ;
}
LRC* search_link(LRC *head,int j)
{
if(head ==NULL)
{
printf("link not find");
return NULL;
}
else
{
LRC *pb=head;
while(pb->time!= j &&pb->next!=NULL)
{
pb=pb->next;
}
if(pb->time==j)
{
return pb;
}
else
{
return NULL;
}
}
return NULL;
}
fun.h
#ifndef __FUN_H__
#define __FUN_H__
typedef struct lrc
{
int time;
char lrc[128];
struct lrc *next;
}LRC;
extern char* read_file(char *name);
extern LRC* insert_link(LRC *head,LRC tmp);
extern void print_link(LRC *head);
extern LRC* search_link(LRC *head,int j);
#endif