使用popen()函数实现对mplayer播放歌曲的歌曲时长获取和当前歌曲进度获取
时间: 2024-03-25 10:38:21 浏览: 20
可以使用 `popen()` 函数打开一个进程并与其进行通信。对于 `mplayer` 播放器,可以使用 `-identify` 参数获取歌曲时长和其他信息,使用 `-slave` 参数启用控制模式,然后通过管道向 `mplayer` 发送命令获取当前歌曲进度。
以下是一个示例程序,该程序通过 `popen()` 打开 `mplayer` 进程并获取歌曲时长和当前进度。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BUF_SIZE 512
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <filename>\n", argv[0]);
return -1;
}
char cmd[BUF_SIZE];
sprintf(cmd, "mplayer -identify -slave %s 2>&1", argv[1]);
FILE *fp = popen(cmd, "r");
if (fp == NULL) {
printf("Failed to open pipe\n");
return -1;
}
int duration = 0;
int position = 0;
while (1) {
char buf[BUF_SIZE];
if (fgets(buf, BUF_SIZE, fp) == NULL) {
break;
}
// 获取歌曲总时长
char *p = strstr(buf, "ID_LENGTH=");
if (p != NULL) {
duration = atoi(p + 10);
}
// 获取当前播放进度
p = strstr(buf, "ANS_TIME_POSITION=");
if (p != NULL) {
position = atoi(p + 17);
}
printf("%s", buf);
fflush(stdout);
}
pclose(fp);
printf("Duration: %d seconds\n", duration);
printf("Position: %d seconds\n", position);
return 0;
}
```
在命令行中运行该程序,例如:
```shell
./get_song_info /path/to/song.mp3
```
该程序将打印 `mplayer` 的输出并输出歌曲总时长和当前进度。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)