Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

MPlayer從模式實戰:命令與管道編程

本文系統說明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的輸出;父進程則起兩個線程,一個從鍵盤讀命令寫入命名管道,一個循環讀取無名管道並打印。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <sys/stat.h>
  6. #include <sys/types.h>
  7. #include <string.h>
  8. int fd_fifo; //命名管道,向mplayer發送命令
  9. int fd_pipe[2]; //無名管道,從mplayer讀取輸出
  10. void *get_pthread(void *arg){
  11.  char buf[100];
  12.  while(1){
  13.   printf("please input you cmd:");
  14.   fflush(stdout);
  15.   fgets(buf, sizeof(buf), stdin);
  16.   buf[strlen(buf)]='\0';
  17.   printf("*%s*\n", buf);
  18.   if(write(fd_fifo, buf, strlen(buf))!=strlen(buf))
  19.    perror("write");
  20.  }
  21. }
  22. void *print_pthread(void *arg){
  23.  char buf[100];
  24.  close(fd_pipe[1]);
  25.  int size=0;
  26.  while(1){
  27.   size=read(fd_pipe[0], buf, sizeof(buf));
  28.   buf[size]='\0';
  29.   printf("th msg read form pipe is %s\n", buf);
  30.  }
  31. }
  32. int main(int argc, char *argv[]){
  33.  int fd;
  34.  char buf[100];
  35.  pid_t pid;
  36.  unlink("/tmp/my_fifo");
  37.  mkfifo("/tmp/my_fifo", O_CREAT|0666);
  38.  perror("mkfifo");
  39.  if (pipe(fd_pipe)<0){
  40.   perror("pipe error\n");
  41.   exit(-1);
  42.  }
  43.  pid=fork();
  44.  if(pid<0){
  45.   perror("fork");
  46.  }
  47.  if(pid==0){ //子進程播放mplayer
  48.   close(fd_pipe[0]);
  49.   dup2(fd_pipe[1], 1);
  50.   fd_fifo=open("/tmp/my_fifo", O_RDWR);
  51.   execlp("mplayer", "mplayer", "-slave", "-quiet", "-input", "file=/tmp/my_fifo", "juhuatai.mpg", NULL);
  52.  }
  53.  else{
  54.   pthread_t tid1, tid2;
  55.   fd_fifo=open("/tmp/my_fifo", O_RDWR);
  56.   if(fd<0)
  57.    perror("open");
  58.   pthread_create(&tid1, NULL, get_pthread, NULL);
  59.   pthread_create(&tid2, NULL, print_pthread, NULL);
  60.   pthread_join(tid1, NULL);
  61.   pthread_join(tid2, NULL);
  62.  }
  63.  return 0;
  64. }

透過命名管道下發命令、無名管道回讀輸出,即可在自有程式中完整掌控MPlayer的播放行為。

Copyright © Linux教程網 All Rights Reserved