Search code examples
phantomjscasperjs

What are ways to play a sound in PhantomJS/CasperJS?


I've been searching the web for more than 3 hours now looking for relevant ways to play an audio file but unfortunately I can't find anything useful. I have a CasperJS that's automating some tasks and I wanted it to play an audio file (e.g. beep.wav) after it completes all the tasks. I wonder if it's possible.

casper.run(function(casper) {
    fs.write( saveDir, JSON.stringify(content, null, '  '), 'w');
    // play an audio file before exiting....
    casper.exit();
});

Solution

  • You need to use Child Process Module to run your script, to play the music.

    I created pl.sh script to play the music:

    #!/bin/bash
    mplayer "/music/downloads2/Technoboy - Into Deep.oga"
    exit 0
    

    Then I created CasperJS script:

    var casper = require('casper').create();
    casper
    .start('http://domu-test-2/node/12', function(){
        var childProcess;
        try {
            childProcess = require("child_process")
        } catch(e){
            console.log(e, "(error)")
        }
        if (childProcess){
            childProcess.execFile("/bin/bash", ["./pl.sh"], null, function(err, stdout, stderr){
                console.log("execFileSTDOUT: "+stdout);
                console.log("execFileSTDERR:",stderr);
            });
            console.log("Shell commands executed")
        } else {
            console.log("Unable to require child process (error)")
        } 
        this.wait(10000)// need to wait to play the sound
    })
    .run();
    

    And then PhantomJS script:

    var page = require('webpage').create();
    page.open('http://domu-test-2/node/12', function() {
        var childProcess;
        try {
            childProcess = require("child_process")
        } catch(e){ 
            console.log(e, "(error)")
        }
        if (childProcess){
            childProcess.execFile("/bin/bash", ["./pl.sh"], null, function(err, stdout, stderr){
                console.log("execFileSTDOUT: "+stdout);
                console.log("execFileSTDERR:",stderr);
            });
            console.log("Shell commands executed")
        } else {
            console.log("Unable to require child process (error)")
        } 
    
        setTimeout(phantom.exit,10000)// need to wait to play the sound
    });