在 PhantomJS/CasperJS 中播放声音的方式有哪些?

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

我已经在网上搜索了 3 个多小时,现在正在寻找播放音频文件的相关方法,但不幸的是我找不到任何有用的方法。我有一个自动执行某些任务的 CasperJS,我希望它在完成所有任务后播放音频文件(例如 beep.wav)。请问有没有可能

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

您需要使用 Child Process Module 到 运行 您的脚本来播放音乐。

我创建了 pl.sh 脚本来播放音乐:

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

然后我创建了 CasperJS 脚本:

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();

然后是 PhantomJS 脚本:

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