当前位置:   article > 正文

【c语言学习】音乐播放器_c语言音乐播放器

c语言音乐播放器

音乐播放器

项目概述

本项目是一个基于c语言的Linux终端纯字符界面音乐播放器,基本功能包括播放歌曲、同步歌词、滚动歌词、显示当前时间以及进度等功能,由字符完成简单的界面显示。

项目准备

首先需要准备歌词和音乐文件,这里拿周杰伦的简单爱为例,歌词需要是**.lrc**格式的,包含时间戳的歌词,因为我们在音乐播放的时候需要用时间来匹配对应的歌词。

[ti:简单爱]
[ar:周杰伦]
[al:范特西]
[by:大脸猫]
[00:04.41]周杰伦 Chow, Jay Jou
[00:10.56]简单爱(台视Star blue蓝星主题曲)
[00:18.48]词:徐若瑄 曲:周杰伦
[00:26.44]说不上为什么 我变得很主动
[00:31.37]若爱上一个人 什么都会值得去做
[02:04.94][00:36.09]我想大声宣布 对你依依不舍
[02:09.97][00:41.26]连隔壁邻居都猜到我现在的感受
[02:14.94][00:46.17]河边的风 在吹着头发 飘动
[02:19.80][00:51.25]牵着你的手 一阵莫名感动
[02:24.61][00:55.86]我想带你 回我的外婆家
[02:28.32][00:59.79]一起看着日落 一直到我们都睡着
[03:34.64][02:34.71][01:05.83]我想就这样牵着你的手不放开
[03:39.68][02:39.34][01:10.71]爱能不能够永远单纯没有悲哀
[03:44.27][02:43.90][01:15.44]我想 带你骑单车
[03:46.74][02:46.60][01:18.05]我想 和你看棒球
[03:49.77][02:49.58][01:20.71]想这样没担忧
[03:51.61][02:51.59][01:22.69]唱着歌 一直走☆
[03:54.38][02:54.35][01:25.57]我想就这样牵着你的手不放开
[03:59.19][02:59.01][01:30.41]爱可不可以简简单单没有伤害
[04:03.77][03:03.73][01:35.04]你 靠着我的肩膀
[04:06.33][03:06.26][01:37.49]你 在我胸口睡着
[04:09.13][03:09.34][01:40.57]像这样的生活
[04:11.36][03:11.26][01:42.66]我爱你 你爱我★
[03:13.76][01:44.97]想~~~ 简!简!单!单! 爱~~~
[03:23.61][01:54.30]想~~~ 简!简!单!单! 爱~~~
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

除了歌词文件和歌曲音频文件外还需要准备音频播放软件mpalyer

sudo apt-get update 
#更新更新源
sudo apt-get install mplayer
#安装mplayer
which mplayer
#查看是否安装成功
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

项目实现

完成准备工作之后就正式进入项目实现阶段。

宏观思路

在这里插入图片描述

上图是QQ音乐的播放界面,可以参考以上界面来完成本项目,上图中包含左侧的专辑封面、右侧上方的标题、歌词、以及下方的音浪特效。本项目只实现了其中一部分,剩下的内容有兴趣的可以自行研究。

要先分析歌词文件,然后再将时间和歌词插入到链表中,在程序运行的时候需要调用系统函数打开mplayer播放器播放音乐,然后根据时间节点显示对应的歌词即可。

读取歌词

首先需要从文件中获取歌词信息,通过文件指针采取随机读取的方法来获取我们需要的歌词信息。

char *read_lrc_file(char *file_name)
{
    FILE *fp = fopen(file_name, "r"); // 权限为只读
    if (NULL == fp)
    {
        perror("fopen");
        return 0;
    }
    // 测量文件长度
    fseek(fp, 0, 2);
    long file_len = ftell(fp);
    rewind(fp);
    char *text = (char *)calloc(1, file_len + 1); // 分配合适的空间
    fread(text, file_len, 1, fp);
    fclose(fp);

    return text;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

按行分割

因为歌词的存储是分行存储,所以我们也需要将文件按行分割,方便后续的标题和歌词分析。

// 歌词切割
void strtok_lrc(char *lrc, char *lrc_buf[])
{
    int i = 0;
    while ((lrc_buf[i] = strtok(lrc_buf[i], "\r\n")) && ++i)
        ;
    return;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

标题分析

歌词文件中包含了标题信息和歌词信息,我们需要将其分离,首先进行标题的分析。

char **analysis_header(char *lrc_buf[])
{
    int i = 0;
    int title_line = 0;
    // 获取题目数量
    while (lrc_buf[i] != NULL)
    {
        if (lrc_buf[i][1] >= 'a' && lrc_buf[i][1] <= 'z')
        {
            title_line++;
        }
        i++;
    }

    // 分配指针数组来存放每个标题行的指针
    char **title = (char **)calloc(title_line + 1, sizeof(char *)); // +1 for NULL
    if (NULL == title)
    {
        perror("calloc");
        return NULL;
    }

    // 遍历每一行,提取标题并存放
    for (i = 0; i < title_line; i++)
    {
        // 假设每行标题最大长度为122(留一个位置给'\0')
        char tle[123];
        sscanf(lrc_buf[i], "%*4c %[^\n]", tle); // 使用格式字符串来避免缓冲区溢出

        // 查找并移除 ']' 字符
        char *addr = strchr(tle, ']');
        if (addr)
        {
            *addr = '\0';
        }

        // 为每个标题行分配内存,并拷贝内容
        title[i] = strdup(tle); // strdup分配内存并拷贝字符串
        if (NULL == title[i])
        {
            perror("strdup");
            // 释放之前分配的内存
            for (int j = 0; j < i; j++)
            {
                free(title[j]);
            }
            free(title);
            return NULL;
        }
    }

    // 确保数组以NULL结尾,作为字符串数组的约定
    title[title_line] = NULL;

    return title;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

因为获取的标题也是多行,所以该函数的返回值是二级指针,注意内存的释放。

// title数组时释放内存
void free_title(char **title)
{
    if (title)
    {
        char **p = title;
        while (*p)
        {
            free(*p++);
        }
        free(title);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

歌词分析和插入

获取了标题之后就需要分析歌词,再将其插入到链表中,所以我们还需要定义结构体song包含歌词和时间并指向next节点,并实现链表的是插入算法。

typedef struct song
{
    int time;
    char lrc[128];

    struct song *next;

} SONG;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
// 链表插入
SONG *insert_link(SONG *head, SONG tmp)
{
    SONG *pi = (SONG *)calloc(1, sizeof(SONG));
    if (NULL == pi)
    {
        perror("calloc");
        return head; // 如果内存分配失败,返回原链表头
    }

    *pi = tmp;       // 复制tmp到pi
    pi->next = NULL; // 新节点next初始化为NULL

    // 如果链表为空,直接返回新节点
    if (NULL == head)
    {
        return pi;
    }

    SONG *pf = head; // pf用于追踪pi应该插入位置的前一个节点
    SONG *pb = head; // pb用于遍历链表寻找插入位置

    // 寻找插入位置
    while (pb != NULL && pb->time < pi->time)
    {
        pf = pb;
        pb = pb->next;
    }

    // 插入新节点
    if (pb == head)
    {
        // 如果pi的时间比头节点还小,将pi插入到头部
        pi->next = head;
        head = pi;
    }
    else
    {
        // 否则,将pi插入到pf之后
        pf->next = pi;
        if (pb != NULL)
        {
            pi->next = pb;
        }
    }

    return head; // 返回更新后的链表头
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

实现了链表的有序插入之后我们可以编写一个链表遍历的算法来验证插入是否成功(这个功能项目不需要)。

// 链表遍历
void print_link(SONG *head)
{
    // 1、判断链表是否存在
    if (NULL == head)
    {
        printf("link not exist\n");
        return;
    }
    else
    {
        // 不能直接动head 所以定义一个指针变量 代替head移动
        SONG *pb = head;
        while (pb != NULL)
        {
            printf("%d %s \n", pb->time, pb->lrc);
            // pb移动到下一个节点
            pb = pb->next;
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

界面和显示

为了实现界面的美观我们可以改变字体的颜色,以及控制光标的位置从而达到我们想要的效果。

#include <stdio.h>
#include <stdlib.h>
#include "console.h"

void cusor_moveto(int x, int y)
{// ESC[y;xH
    printf("\033[%d;%dH",y,x);
    fflush(stdout);
} 

//保存光标位置
void cusor_get_pos(void)
{// ESC[s
    printf("\033[s");
    fflush(stdout);
} 

//恢复光标位置
void cusor_set_pos(void)
{// ESC[u
    printf("\033[u");
    fflush(stdout);
} 
void cusor_hide(void)
{
	printf("\033[?25l");
}
//清屏
void clear_screen(void)
{// ESC[2J
    printf("\033[2J");
    fflush(stdout);
}

/*
COLOR_RED              红
COLOR_BLACK            黑
COLOR_GREEN            绿
COLOR_BLUE             蓝
COLOR_YELLOW           黄
COLOR_WHITE            白
COLOR_CYAN             青
COLOR_MAGENTA          洋红
*/
//设置前景颜色
void set_fg_color(int color)
{// ESC[#m
    printf("\033[%dm",color);
    fflush(stdout);
}

//设置背景颜色
void set_bg_color(int color)
{// ESC[#m
    printf("\033[%dm",(color+10));
    fflush(stdout);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
#ifndef  _CONSOLE_H_
#define  _CONSOLE_H_

#define     COLOR_RED              31
#define     COLOR_BLACK            30
#define     COLOR_GREEN            32
#define     COLOR_BLUE             34
#define     COLOR_YELLOW           33
#define     COLOR_WHITE            37
#define     COLOR_CYAN             36
#define     COLOR_MAGENTA          35
/*
COLOR_RED              红
COLOR_BLACK            黑
COLOR_GREEN            绿
COLOR_BLUE             蓝
COLOR_YELLOW           黄
COLOR_WHITE            白
COLOR_CYAN             青
COLOR_MAGENTA          洋红
*/

extern void cusor_moveto(int x, int y);//光标跳转到 y行 x列
extern void cusor_get_pos(void);//保存光标位置
extern void cusor_hide(void);
extern void cusor_set_pos(void);//恢复光标位置
extern void clear_screen(void);//清屏
extern void set_fg_color(int color);//设置字体前景色
extern void set_bg_color(int color);//设置字体背景色

#endif	//_CONSOLE_H_



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

启动mplayer

void mplayer_play(char *song_path)
{
	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);
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

最终实现

main函数中调用其他函数并实现歌词滚动播放、进度显示、模拟时钟,以及简单的界面美化。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lrc.h"
#include "start_mplayer.h"
#include "console.h"
#include <unistd.h>
#include "background.h"
#include <time.h>
int main(int argc, char const *argv[])
{
    SONG *head = NULL;
    char *lrc = read_lrc_file("简单爱.lrc"); // 读歌词

    char *lrc_buf[128] = {lrc};

    strtok_lrc(lrc, lrc_buf); // 逐行切割

    system("clear");           // 清屏
    print_background(100, 40); // 绘制背景框

    set_fg_color(34); // 设置前景颜色

    char **titles = analysis_header(lrc_buf); // 分析标题
    if (titles)
    {
        for (int i = 0; titles[i]; i++)
        {
            cusor_moveto(47, 10 + i);
            printf("%s", titles[i]); // 在固定位置逐行输出标题
        }
        free_title(titles); // 释放内存
    }
    head = analysis_lrc(lrc_buf, head); // 逐行分析歌词并插入链表

    mplayer_play("简单爱.mp3");

    int timestamp = 0;    // 时间戳
    int time_total = 271; // 总时间

    int visible_lines = 4; // 歌词显示行数
    SONG *current = head;  // 从头节点开始遍历链表
    SONG *temp;
    int current_line = 0; // 当前显示歌词的起始行

    while (timestamp <= time_total)
    // while (1)
    {
        cusor_moveto(43, 30);
        printf("%02d:%02d // %02d:%02d", timestamp / 60, timestamp % 60, time_total / 60, time_total % 60); // 显示时间
        cusor_moveto(49, 32);
        printf("%d%%", (int)(timestamp / (float)time_total * 100)); // 进度条

        cusor_hide(); // 隐藏光标
        fflush(stdout);
        // 歌词滚动播放
        temp = head;
        while (temp != NULL && temp->time <= timestamp)
        {
            current = temp;
            temp = temp->next;
        }

        // 计算当前显示的四行歌词
        SONG *start_line = current;
        for (int i = 0; i < current_line && start_line != NULL; i++)
        {
            start_line = start_line->next;
        }

        srand(time(NULL));

        for (int i = 0; i < visible_lines && start_line != NULL; i++)
        {
            int random_num = rand() % 6;
            cusor_moveto(40, 15 + i);
            set_fg_color(32 + random_num);
            printf("\033[K");                // 清空当前行
            printf("%s\n", start_line->lrc); // 打印歌词
            cusor_moveto(100, 15 + i);
            // set_fg_color(37);
            printf("#"); // 补上空缺
            fflush(stdout);
            start_line = start_line->next;
        }

        // 判断是否需要滚动歌词
        if (current->next != NULL && timestamp >= current->next->time)
        {
            current_line++;
            if (current_line >= visible_lines || current->next->next == NULL)
                current_line = 0;
        }

        sleep(1);
        timestamp++;
        cusor_get_pos();
        // 显示光标
    }
    cusor_set_pos();
    set_fg_color(37); // 改回前景色
    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104

Makefile

为了简化编译过程使用Makefile

EXEC=main
GCC=gcc
OBJ=main.o lrc.o start_mplayer.o console.o background.o
FLAGS=-Wall
$(EXEC):$(OBJ)
	$(GCC) $^ -o $@ $(FLAGS)
%.o:%.c
	$(GCC) -c $< -o $@ $(FLAGS)
clean:
	rm $(EXEC) $(OBJ)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

成果展示

在这里插入图片描述

如上图,当程序运行时音乐开始播放,歌曲标题信息会在固定位置显示,歌词会随着音乐的播放滚动显示对应的歌词,歌词的颜色会随机变化。下方包括进度显示和时间,当歌曲播放完成后进度会显示100%并且程序会结束运行。

总结

本项目是采用c语言完成的Linux环境下的字符界面音乐播放程序,实现了简单的界面、歌曲标题信息显示、歌词滚动显示,进度信息以及时间功能。本项目仅作学习c语言的练习之用,相较于常见的音乐播放器显得十分简漏,缺少很多功能并且还有一些bug也并未修复,有兴趣的可以自行改进完善。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/1006914
推荐阅读
相关标签
  

闽ICP备14008679号