我正在尝试执行播放歌曲的shell脚本。当我在命令行中键入以下内容时,一切都很好:
/home/pi/startsong.sh /path/to/track
但是,我正在尝试通过Java应用程序执行脚本,但根本没有得到任何响应。这就是我正在做的事情:
public void begin(String song) throws IOException, InterruptedException {
//Split song title
String[] cmd = song.split("");
StringBuilder sb = new StringBuilder();
//Ignore for now, this is just about sorting out titles with spaces, but irrelevant
for (int i = 0; i < cmd.length; i++) {
if (cmd[i].equals(" ")) {
cmd[i] = " ";
}
sb.append(cmd[i]);
}
//Initiate bash script whilst passing song title as argument
String command = "/home/pi/startsong.sh " + sb.toString();
System.out.println(command);
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(command);
p.waitFor();
System.out.println("Playing song...");
}
当我运行程序时,它打印的命令(正如我所要求的)与我输入命令行的命令完全一样。
为什么脚本不执行?
我尝试过使用ProcessBuilder
并调用直接播放曲目的程序,但都无法正常工作。为简单起见,我正在用一条轨道进行测试,该轨道的路径没有空格或奇怪的字符。
我尝试将/bin/bash -c
添加到command
字符串
仅供参考我在运行Raspbian的Raspberry Pi上运行Java 8。播放曲目的节目是omxplayer。
任何帮助都是最感激的,因为我一整天都在坚持这一点!
谢谢!
答案 0 :(得分:0)
好的,感谢@Etan我已经设法解决了这个问题。这样修改了代码,使用InputStream阅读器识别文件名的问题:
public void begin(String song) throws IOException, InterruptedException {
//Split song title
String[] cmd = song.split("");
StringBuilder sb = new StringBuilder();
//Ignore for now
for (int i = 0; i < cmd.length; i++) {
if (cmd[i].equals(" ")) {
cmd[i] = " ";
}
sb.append(cmd[i]);
}
//Initiate bash script whilst passing song title as argument
System.out.println("Playing song...");
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/home/pi/startsong.sh", "/home"+sb.toString());
final Process process = pb.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Program terminated!");
}