How can I use child_process.spawn to pause a media player?

I'm trying to control mplayer with a node.js program using child_process.spawn.

I am having trouble resuming the playback after I paused it. For some reason, an exit event is sent even though mplayer hasn't finished playing.

What am I doing wrong?

The following code works fine (I can hear the music play) until the second pause command.

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' );
}

The first output for mplayer.stdin looks like this:

{ _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 }

The second one like this:

{ _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 }

I get the following error:

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)

Without attempting to test or debug a few thoughts come to mind:

Use mplayer's slave mode. You do this by giving it the -slave flag at startup. See http://www.mplayerhq.hu/DOCS/tech/slave.txt for more info.

Setup code to show what mplayers wants to tell you. Might be more meaningful than watching the socket status.

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' );
}