user934801
user934801

Reputation: 1139

how to play sound on raspberry pi - after startup without login

i need to play sound on the raspberry pi with a node.js script. Everything is fine when i'm starting the script from the commandline myself. When i run the same script after startup out of the /etc/rc.local script i see my running process when doing "ps aux" but i cant hear any sound. I also tried to start the node script after 40 seconds, because i thought that there was too less time for some initialization stuff or something, but within this time i could start the script from the command line and hear sound...

i tried both users: root and pi. They both work from the cmd (because the user that runs the script after the autostart is the root user)

i linked my programm to /usr/bin/node because if not the process wasnt able to start on startup.

i forced the raspberryPi to use the sereo jack: amixer cset numid=3 1

my node.js code is:

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

for the startup i tried: as a cronjob, after crontab -e i attached: @reboot /opt/node/bin/forever start /var/www/node/residenz/server.js

i also tried the same inside the file /etc/rc.local : /opt/node/bin/forever start /var/www/node/residenz/server.js

thanks for any help!

Upvotes: 1

Views: 4534

Answers (2)

mlhDev
mlhDev

Reputation: 2395

I had the same problem, and this question (and analyzing the answer) gave me hope that it was possible, but for me it was the paths that was a problem - I was using a relative path but the working directory (and perhaps user?) being executed under cron needed the path to the file be absolute. BTW, I used cron, python, and pygame (pygame.mixer.music) and was able to make it work.

My testing program (pygame.mixer.Sound did not work but I believe that was because I was using an MP3 instead of a 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"

In cron, I had @reboot python /home/pi/soundtest.py music & and it played the file on boot up.

Upvotes: 1

user934801
user934801

Reputation: 1139

Just in case, that anyone else has the same Problem i want to share my final solution. I simply did the functionality with python. For the startup, i put the line which starts the python script into the file /etc/rc.local

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# server.py
import RPi.GPIO as GPIO
import subprocess
import time
import serial
from random import randint
port = serial.Serial("/dev/ttyACM0", baudrate=9600, timeout=0)
PATH=[4]
PATH.append("/var/www/node/Boom1.mp3")
PATH.append("/var/www/node/Boom2.mp3")
PATH.append("/var/www/node/Boom3.mp3")
PATH.append("/var/www/node/Boom4.mp3")

def main():
  count = 0
  while True:
    value=0
    line = port.readlines()

    if( len(line)!= 0 and count < 4 ):
      try:
        job=subprocess.Popen(["mpg321", returnPath()], stdin=subprocess.PIPE)
        time.sleep( float(line[0])/10 )
      except:
        print("cant play soundfile")
    def returnPath():
      x = randint(1,4)
      return PATH[x]

if __name__ == '__main__':
  main()

Upvotes: 0

Related Questions