반응형

이전 포스팅: https://gusdnr69.tistory.com/category/IOT%EA%B0%9C%EB%B0%9C/node.js

 

'IOT개발/node.js' 카테고리의 글 목록

코딩, 개발, 애니덕질

gusdnr69.tistory.com

 

play-sound는  mp3 파일에 한해서 재생이 됩니다.

다양한 음원 파일을 재생할 수 있는 라이브러리를 소개하겠습니다.

 

https://dyclassroom.com/reference-javascript/work-with-audio-in-javascript-using-howler-js

 

Work with audio in JavaScript using Howler.js - Reference JavaScript - DYclassroom | Have fun learning :-)

In this tutorial we will learn about Howler.js which makes working with audio in JavaScript easy and reliable across all platforms. Click here to visit Howler.js GitHub repository. Install If you have Node and NPM installed then use the following command i

dyclassroom.com

 

Howler.js 입니다. 웹 UI를 통해서 mp3외에 다른 형식의 음원파일도 재생이 가능합니다.

 

 

 

 

저는 wav파일을 재생하기 위해서 

node-aplay 

를 사용하였습니다.

 

 

설치 절차

sudo apt-get update
sudo apt-get upgrade
sudo rpi-update
sudo apt-get install alsa-base alsa-utils
sudo npm install node-aplay

 

 

 

예시 코드

var Sound = require('node-aplay');
 
// fire and forget:
new Sound('/path/to/the/file/filename.wav').play();
 
// with ability to pause/resume:
var music = new Sound('/path/to/the/file/filename.wav');
music.play();
 
setTimeout(function () {
    music.pause(); // pause the music after five seconds
}, 5000);
 
setTimeout(function () {
    music.resume(); // and resume it two seconds after pausing
}, 7000);
 
// you can also listen for various callbacks:
music.on('complete' function () {
    console.log('Done with playback!');
});

 

 

 pause나 resume은 미리 변수에 sound 객체를 저장해놓아야만 가능합니다. 

setTimeout 없이 사용하셔도 무방합니다.

 

 

반응형
반응형

play-sound 라는 npm을 사용해서 라즈베리파이에서 node.js를 통해서 음악을 틀 수 있습니다.

 

 

sudo npm install play-sound

 

해당 모듈을 설치하시고!

 

 

예시코드입니다. 

var player = require('play-sound')(opts = {})
 
// $ mplayer foo.mp3 
player.play('foo.mp3', function(err){
  if (err) throw err
})
 
// { timeout: 300 } will be passed to child process
player.play('foo.mp3', { timeout: 300 }, function(err){
  if (err) throw err
})
 
// configure arguments for executable if any
player.play('foo.mp3', { afplay: ['-v', 1 ] /* lower volume for afplay on OSX */ }, function(err){
  if (err) throw err
})
 
// access the node child_process in case you need to kill it on demand
var audio = player.play('foo.mp3', function(err){
  if (err && !err.killed) throw err
})
audio.kill()

 

이런 방식으로 사용해주시면 됩니다. foo.mp3대신 파일경로와 원하는 mp3파일을 넣어주시면 됩니다.

쓰레드 단위로 돌아가기 때문에 노래가 중복해서 틀어질 수 있습니다. 

적절한 예외처리를 해주셔야 할 것이고 

 

음악을 끄는 코드는 제일 아래에 코드인 

audio.kill()

입니다.

 

 

반응형
반응형

 

node.js를 사용해서 LED와 같은 다양한 장치를 쉽게 제어할 수 있습니다.

 

node.js 개념이 궁금하시다면?

https://gusdnr69.tistory.com/32?category=763917

 

node.js 란? 🤷‍♂️

JavaScript 언어는 주로 어디에 사용될까요?? 웹프로그래밍에서 동적으로 움직이는 화면들에 사용됩니다. 그리고 새로고침이 되지 않았는데 동적으로 움직이는 텍스트들에도 사용됩니다. JavaScript도 하나의 프로..

gusdnr69.tistory.com

 

 

soketio를 사용하는 방법도 있지만, 기본적인 방법을 우선 설명드리겠습니다.

 

3색 LED와 같은 경우 2가지가 있습니다.  커먼 캐소드 방식과 커먼 애노드 방식입니다. 각각 긴 단자를 gnd나 5v에 연결하시면 됩니다.

 

커먼캐소드 코드입니다.

var http = require('http').createServer(handler); //require http server, and create server with function handler()
var fs = require('fs'); //require filesystem module
var io = require('socket.io')(http) //require socket.io module and pass the http object (server)
var Gpio = require('pigpio').Gpio, //include pigpio to interact with the GPIO
ledRed = new Gpio(4, {mode: Gpio.OUTPUT}), //use GPIO pin 4 as output for RED
ledGreen = new Gpio(17, {mode: Gpio.OUTPUT}), //use GPIO pin 17 as output for GREEN
ledBlue = new Gpio(27, {mode: Gpio.OUTPUT}), //use GPIO pin 27 as output for BLUE
redRGB = 0, //set starting value of RED variable to off (0 for common cathode)
greenRGB = 0, //set starting value of GREEN variable to off (0 for common cathode)
blueRGB = 0; //set starting value of BLUE variable to off (0 for common cathode)

//RESET RGB LED
ledRed.digitalWrite(0); // Turn RED LED off
ledGreen.digitalWrite(0); // Turn GREEN LED off
ledBlue.digitalWrite(0); // Turn BLUE LED off

http.listen(8080); //listen to port 8080

function handler (req, res) { //what to do on requests to port 8080
  fs.readFile(__dirname + '/public/rgb.html', function(err, data) { //read file rgb.html in public folder
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
      return res.end("404 Not Found");
    }
    res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
    res.write(data); //write data from rgb.html
    return res.end();
  });
}

io.sockets.on('connection', function (socket) {// Web Socket Connection
  socket.on('rgbLed', function(data) { //get light switch status from client
    console.log(data); //output data from WebSocket connection to console

    //for common cathode RGB LED 0 is fully off, and 255 is fully on
    redRGB=parseInt(data.red);
    greenRGB=parseInt(data.green);
    blueRGB=parseInt(data.blue);

    ledRed.pwmWrite(redRGB); //set RED LED to specified value
    ledGreen.pwmWrite(greenRGB); //set GREEN LED to specified value
    ledBlue.pwmWrite(blueRGB); //set BLUE LED to specified value
  });
});

process.on('SIGINT', function () { //on ctrl+c
  ledRed.digitalWrite(0); // Turn RED LED off
  ledGreen.digitalWrite(0); // Turn GREEN LED off
  ledBlue.digitalWrite(0); // Turn BLUE LED off
  process.exit(); //exit completely
});

 

커먼 애노드코드입니다.

var http = require('http').createServer(handler); //require http server, and create server with function handler()
var fs = require('fs'); //require filesystem module
var io = require('socket.io')(http) //require socket.io module and pass the http object (server)
var Gpio = require('pigpio').Gpio, //include pigpio to interact with the GPIO
ledRed = new Gpio(4, {mode: Gpio.OUTPUT}), //use GPIO pin 4 as output for RED
ledGreen = new Gpio(17, {mode: Gpio.OUTPUT}), //use GPIO pin 17 as output for GREEN
ledBlue = new Gpio(27, {mode: Gpio.OUTPUT}), //use GPIO pin 27 as output for BLUE
redRGB = 255, //set starting value of RED variable to off (255 for common anode)
greenRGB = 255, //set starting value of GREEN variable to off (255 for common anode)
blueRGB = 255; //set starting value of BLUE variable to off (255 for common anode)

//RESET RGB LED
ledRed.digitalWrite(1); // Turn RED LED off
ledGreen.digitalWrite(1); // Turn GREEN LED off
ledBlue.digitalWrite(1); // Turn BLUE LED off

http.listen(8080); //listen to port 8080

function handler (req, res) { //what to do on requests to port 8080
  fs.readFile(__dirname + '/public/rgb.html', function(err, data) { //read file rgb.html in public folder
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
      return res.end("404 Not Found");
    }
    res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
    res.write(data); //write data from rgb.html
    return res.end();
  });
}

io.sockets.on('connection', function (socket) {// Web Socket Connection
  socket.on('rgbLed', function(data) { //get light switch status from client
    console.log(data); //output data from WebSocket connection to console

    //for common anode RGB LED  255 is fully off, and 0 is fully on, so we have to change the value from the client
    redRGB=255-parseInt(data.red);
    greenRGB=255-parseInt(data.green);
    blueRGB=255-parseInt(data.blue);

    console.log("rbg: " + redRGB + ", " + greenRGB + ", " + blueRGB); //output converted to console

    ledRed.pwmWrite(redRGB); //set RED LED to specified value
    ledGreen.pwmWrite(greenRGB); //set GREEN LED to specified value
    ledBlue.pwmWrite(blueRGB); //set BLUE LED to specified value
  });
});

process.on('SIGINT', function () { //on ctrl+c
  ledRed.digitalWrite(1); // Turn RED LED off
  ledGreen.digitalWrite(1); // Turn GREEN LED off
  ledBlue.digitalWrite(1); // Turn BLUE LED off
  process.exit(); //exit completely
});

 

write함수의 사용법이 조금 다른 것이 특징입니다. 

 

아래 링크에 더욱 자세하게 설명되어있으니 참고하시면 좋을 것 같습니다. 

화이팅 :) 

 

참고자료:https://www.w3schools.com/nodejs/nodejs_raspberrypi_rgb_led_websocket.asp

 

Node.js Raspberry Pi RGB LED and WebSocket

Node.js Raspberry Pi RGB LED with WebSocket Using Pulse-Width Modulation In the previous chapters we have learned how to use WebSocket, and how to use GPIO to turn LEDs on and off. In this we will use chapter we use a RGB LED, with PWM (Pulse-width modulat

www.w3schools.com

 

반응형
반응형

JavaScript 언어는 주로 어디에 사용될까요??

웹프로그래밍에서 동적으로 움직이는 화면들에 사용됩니다. 그리고 새로고침이 되지 않았는데 동적으로 움직이는 텍스트들에도 사용됩니다.  JavaScript도 하나의 프로그래밍 언어이기에 프론트단에서 그러한 움직을 만들수 있는 것입니다. 

 

 

JavaScript를 크롬(Chrome)같은 브라우저에서만 쓰는 것이 아닌 브라우저 밖. 즉, 내 컴퓨터에서 다양한 용도로 확장하기 위해 만들어진 것이 바로 Node.js입니다. Node.js를 이용하면 Python과 같이 내 컴퓨터에서 File System를 이용할 수 있고, 서버를 만들 수도 있고 크롤링도 할 수 있습니다. JavaScript도 Python과 같은 프로그래밍 언어이기 때문입니다.

 

 

 

Node.js를 이용하여 Express같은 라이브러리를 이용해서 서버를 만들곤하지만, Node.js 자체는 웹서버가 아닙니다.  Node.js는 자바스크립트 런타임(JavaScript Runtime)으로 Node.js는 웹 서버를 만들 수 있는 하나의 방법에 불과합니다.

 

 

 

Node.js의 특징

1.비동기 I/O 처리: Node.js 라이브러리의 모든 API는 비동기식(async)입니다, 멈추지 않는다는거죠 (Non-blocking). Node.js 기반 서버는 API가 실행되었을때, 데이터를 반환할때까지 기다리지 않고 다음 API 를 실행합니다. 그리고 이전에 실행했던 API가 결과값을 반환할 시, Node.js의 이벤트 알림 메커니즘을 통해 결과값을 받아옵니다.

 

 

2. 빠른 속도: 구글 크롬(Google Chrome)의 V8 자바스크립트 엔진(JavaScript Engine)을 사용하여 빠른 코드 실행을 제공합니다.

 

 

3. 단일 쓰레드와 뛰어난 확장성: Node.js는 이벤트 루프와 함께 단일 쓰레드 모델을 사용합니다. 이벤트 메커니즘은 서버가 멈추지않고 반응하도록 해주어 서버의 확장성을 키워줍니다. 반면, 아파치(Apache)같은 일반적인 웹서버는 요청을 처리하기 위하여 제한된 쓰레드를 생성합니다. Node.js 는 쓰레드를 한개만 사용하고 아파치(Apache)같은 웹서버보다 훨씬 많은 요청을 처리할 수 있습니다.

 

Node.js를 쓰기 적합한 곳

다음과 같은 경우에 Node.js를 사용할 경우 좋은 효율성을 발휘할 수 있습니다.

  • 알림이나 실시간 대화같이 같이 데이터의 실시간 처리가 필요한 애플리케이션
  • 사용자의 입력과 출력이 잦은 애플리케이션
  • 데이터 스트리밍 애플리케이션
  • JSON API기반의 애플리케이션
  • 단일 페이지 기반의 애플리케이션

웹외에도, 장치를 조작하는데도 많이 사용됩니다. 

다음부터의 제 포스팅에서는 라즈베리파이에서의 node.js를 활용한 정보전달 및 장치제어에 초점을 두고 포스팅 하겠습니다.

반응형

+ Recent posts