如何使用child_process.spawn暂停媒体播放器?

时间:2012-10-04 22:05:52

标签: javascript node.js stdin

我正在使用child_process.spawn尝试使用node.js程序control mplayer

暂停后我无法恢复播放。出于某种原因,即使mplayer还没有完成播放,也会发送exit事件。

我做错了什么?

以下代码可以正常工作(我可以听到音乐播放)直到第二个暂停命令。

var spawn = require( 'child_process' ).spawn;
var mplayer;
var file = '/Users/snorpey/Music/Blink-182/Untitled/01 Feeling This.m4a';

mplayer = spawn( 'mplayer', [ file ] );
mplayer.on( 'exit', function(){ console.log( 'EXIT.' ); } );

setTimeout( pause, 5000 );
setTimeout( pause, 9000 );

function pause()
{
    console.log( 'PAUSE', mplayer.stdin );
    mplayer.stdin.write( 'p\n' );
}

mplayer.stdin的第一个输出如下所示:

{ _handle: 
   { writeQueueSize: 0,
     owner: [Circular],
     onread: [Function: onread] },
  _pendingWriteReqs: 0,
  _flags: 0,
  _connectQueueSize: 0,
  destroyed: false,
  errorEmitted: false,
  bytesRead: 0,
  _bytesDispatched: 0,
  allowHalfOpen: undefined,
  writable: true,
  readable: false }

第二个是这样的:

{ _handle: null,
  _pendingWriteReqs: 0,
  _flags: 0,
  _connectQueueSize: 0,
  destroyed: true,
  errorEmitted: false,
  bytesRead: 0,
  _bytesDispatched: 2,
  allowHalfOpen: undefined,
  writable: false,
  readable: false,
  _connecting: false,
  _connectQueue: null,
  _idleNext: null,
  _idlePrev: null,
  _idleTimeout: -1 }

我收到以下错误:

events.js:66
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: This socket is closed.
    at Socket._write (net.js:517:19)
    at Socket.write (net.js:509:15)
    at Object.pause [as _onTimeout] (/Users/snorpey/Sites/Development/mplayer/pause.js:14:16)
    at Timer.list.ontimeout (timers.js:101:19)

1 个答案:

答案 0 :(得分:2)

不试图测试或调试一些想法:

使用mplayer的从属模式。你通过在启动时给它-slave标志来做到这一点。有关详细信息,请参阅http://www.mplayerhq.hu/DOCS/tech/slave.txt

设置代码以显示mplayers想要告诉您的内容。可能比观看套接字状态更有意义。

var spawn = require( 'child_process' ).spawn;
var mplayer;
var file = '/Users/snorpey/Music/Blink-182/Untitled/01 Feeling This.m4a';

mplayer = spawn( 'mplayer', [ '-slave', file ] );
mplayer.on( 'exit', function () { console.log( 'EXIT.' ); } );

// obviously you'll want something smarter than just logging...
mplayer.stdout.on('data', function (data) { console.log('mplayer stdout: ' + data); });
mplayer.stderr.on('data', function (data) { console.log('mplayer stderr: ' + data); });

setTimeout( pause, 5000 );
setTimeout( pause, 9000 );

function pause() {
    console.log( 'PAUSE' );
    mplayer.stdin.write( 'pausing\n' );
}