本文系統說明MPlayer的slave(從)模式,並給出在實際編程中如何透過管道對其進行控制的完整示例。
一、簡介
默認情況下,MPlayer從鍵盤獲取控制信息。此外它還提供了一種更靈活的控制方式——slave模式。在該模式下,MPlayer作為後台程式運行,不再截獲鍵盤事件,而是從標準輸入讀取以換行符(\n)分隔的命令。
二、操作方法
執行mplayer -input cmdlist可打印出當前MPlayer支持的所有slave命令。
方法一:從控制台輸入(測試用)
運行mplayer -slave -quiet <movie>,其中-slave啟動從模式,-quiet避免冗餘輸出。常用指令包括:loadfile(加載歌曲)、volume 100 1(設定音量)、mute 1/0(靜音開關)、pause(暫停/繼續)、get_time_length(返回時長,秒)、seek value(跳轉到指定秒數)、get_percent_pos(返回0–100的百分比)、get_time_pos(當前位置秒數)、get_file_name,以及get_meta_album/artist/comment/genre/title/year等元數據查詢。
方法二:從命名管道輸入(編程用)
mkfifo /tmp/fifofile
mplayer -slave -input file=/tmp/fifofile <movie>
使用者只需向管道寫入slave命令,即可實現相應功能。
三、完整編程示例
思路是:主進程創建一個無名管道和一個有名管道,fork出子進程啟動MPlayer,並通過命名管道通信、通過無名管道回讀MPlayer的輸出;父進程則起兩個線程,一個從鍵盤讀命令寫入命名管道,一個循環讀取無名管道並打印。
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <string.h>
- int fd_fifo; //命名管道,向mplayer發送命令
- int fd_pipe[2]; //無名管道,從mplayer讀取輸出
- void *get_pthread(void *arg){
- char buf[100];
- while(1){
- printf("please input you cmd:");
- fflush(stdout);
- fgets(buf, sizeof(buf), stdin);
- buf[strlen(buf)]='\0';
- printf("*%s*\n", buf);
- if(write(fd_fifo, buf, strlen(buf))!=strlen(buf))
- perror("write");
- }
- }
- void *print_pthread(void *arg){
- char buf[100];
- close(fd_pipe[1]);
- int size=0;
- while(1){
- size=read(fd_pipe[0], buf, sizeof(buf));
- buf[size]='\0';
- printf("th msg read form pipe is %s\n", buf);
- }
- }
- int main(int argc, char *argv[]){
- int fd;
- char buf[100];
- pid_t pid;
- unlink("/tmp/my_fifo");
- mkfifo("/tmp/my_fifo", O_CREAT|0666);
- perror("mkfifo");
- if (pipe(fd_pipe)<0){
- perror("pipe error\n");
- exit(-1);
- }
- pid=fork();
- if(pid<0){
- perror("fork");
- }
- if(pid==0){ //子進程播放mplayer
- close(fd_pipe[0]);
- dup2(fd_pipe[1], 1);
- fd_fifo=open("/tmp/my_fifo", O_RDWR);
- execlp("mplayer", "mplayer", "-slave", "-quiet", "-input", "file=/tmp/my_fifo", "juhuatai.mpg", NULL);
- }
- else{
- pthread_t tid1, tid2;
- fd_fifo=open("/tmp/my_fifo", O_RDWR);
- if(fd<0)
- perror("open");
- pthread_create(&tid1, NULL, get_pthread, NULL);
- pthread_create(&tid2, NULL, print_pthread, NULL);
- pthread_join(tid1, NULL);
- pthread_join(tid2, NULL);
- }
- return 0;
- }
透過命名管道下發命令、無名管道回讀輸出,即可在自有程式中完整掌控MPlayer的播放行為。