我需要使用 node.js 脚本在树莓派上播放声音。当我自己从命令行启动脚本时,一切都很好。当我从/etc/rc.local 脚本启动后运行相同的脚本时,我在执行“ps aux”时看到正在运行的进程,但我听不到任何声音。我还尝试在 40 秒后启动 Node 脚本,因为我认为一些初始化内容或其他东西的时间太少了,但在这段时间内我可以从命令行启动脚本并听到声音...
我尝试了两个用户:root 和 pi。它们都在cmd下工作(因为自动启动后运行脚本的用户是root用户)
我将我的程序链接到/usr/bin/node,因为如果没有,该进程将无法在启动时启动。
我强制 raspberryPi 使用 sereo 插孔:amixer cset numid=3 1
我的node.js代码是:
var fs = require("fs");
var lame = require("lame");
var Speaker = require("speaker");
var SerialPort = require("serialport").SerialPort;
var playing = false;
var stream = [];
stream[0] = "sound1.mp3";
stream[1] = "sound2.mp3";
stream[2] = "sound3.mp3";
stream[3] = "sound4.mp3";
var getCurrentStream = function(){
var i = Math.round( Math.random() * 3)
return stream[i];
}
var serialPort = new SerialPort("/dev/ttyACM0", {
baudrate: 9600
}, false);
serialPort.open(function(){
console.log("open");
serialPort.on("data", function(data){
console.log("data received"+data);
if(!playing){
try{
var currentStream = fs.createReadStream( getCurrentStream() );
var speaker = new Speaker();
speaker.on('finish', function(){
playing = false;
});
currentStream.pipe(new lame.Decoder()).pipe(speaker);
playing = true;
}
catch(e){
console.log("Error: "+e);
}
}
});
});
对于我尝试过的启动: 作为一个 cronjob,在 crontab -e 之后我附加了: @reboot/opt/node/bin/forever start/var/www/node/residenz/server.js
我也在文件/etc/rc.local 中尝试了相同的操作: /opt/node/bin/forever start/var/www/node/residenz/server.js
感谢您的帮助!
最佳答案
我遇到了同样的问题,这个问题(并分析答案)给了我希望这是可能的,但对我来说,路径是一个问题 - 我使用的是相对路径,但工作目录(和也许是用户?)在 cron 下执行需要文件的绝对路径。顺便说一句,我使用了 cron、python 和 pygame (pygame.mixer.music) 并且能够使其工作。
我的测试程序(pygame.mixer.Sound 不起作用,但我相信这是因为我使用的是 MP3 而不是 WAV)
import pygame
import time
import os
import sys
#soundFile = "alarm.mp3" # BAD
soundFile = "/home/pi/alarm.mp3" # GOOD
channel = None
if len(sys.argv) > 1:
pygame.mixer.init(44100, -16, 2, 4096)
if sys.argv[1] == "music":
print "Testing pygame.mixer"
pygame.mixer.music.load(soundFile)
pygame.mixer.music.set_volume(1.0)
pygame.mixer.music.play()
elif sys.argv[1] == "sound":
print "Testing pygame.sound"
pygame.mixer.init()
s = pygame.mixer.Sound(soundFile)
s.set_volume(1.0)
channel = s.play()
elif sys.argv[1] == "mpg":
print "Using mpg321 Player"
os.system("mpg321 " + soundFile)
else:
print "Using OMX Player"
os.system("omxplayer " + soundFile)
print "Execution control has returned"
while pygame.mixer.get_busy() or pygame.mixer.music.get_busy() or \
(channel is not None and channel.get_busy()):
continue
pygame.mixer.quit()
else:
print "Unknown option. Options are omx, mpg, music, or sound"
在 cron 中,我有 @reboot python/home/pi/soundtest.py music &
并且它在启动时播放了该文件。
关于node.js - 如何在树莓派上播放声音 - 启动后无需登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23888529/