SmartCradle v1
Baby smart cradle
microphone.c
Go to the documentation of this file.
1
10#include <sndfile.h>
11#include <sys/syslog.h>
12#include <sys/wait.h>
13#include "../inc/microphone.h"
14
15#define THRESHOLD -35 // Audio threshold [dB]
16#define LIMIT 3
17
19{
20 int ret = 0;
21
22 ret = system("ffmpeg \
23 -f alsa -ac 1 -ar 44100 -i plughw:0,0 \
24 -c:a copy \
25 -t 2 -y \
26 /etc/audiorecord.wav");
27
28 // return value from the command on the upper 8-bits of the return value
29 // 0 on sucess, 1 on failure
30 return WEXITSTATUS(ret);
31}
32
42{
43 char *inFileName;
44 SNDFILE *inFile;
45 SF_INFO inFileInfo;
46 double sum = 0;
47 int i;
48
49 inFileName = "/etc/audiorecord.wav"; // Audio file name
50
51 inFile = sf_open(inFileName, SFM_READ, &inFileInfo); // Open the .wav file with read permissions
52 if (inFile == NULL)
53 return ERR_OPEN;
54
55 int samples = inFileInfo.frames * inFileInfo.channels; // Get the size of the audio file in samples
56 double buffer[samples];
57
58 if (sf_read_double(inFile, buffer, samples) != samples) // Read the audio file values to the buffer
59 return ERR_READ;
60
61 sf_close(inFile);
62
63 // Calculate the RMS value of the audio sample
64 for (i = 0; i < samples; i++)
65 {
66 sum += buffer[i] * buffer[i];
67 }
68 double ms = sqrt(sum) / (double)samples;
69
70 return 10 * log10(ms); // Returns in dB
71}
72
73int processAudio(double *loudness)
74{
75 double ret = 0;
76 static u_int8_t crying_counter = 0;
77
78 ret = calculateLoudness();
79
80 if ((int)ret == ERR_OPEN || (int)ret == ERR_READ)
81 return (int)ret;
82
83 *loudness = ret;
84
85 if (ret >= THRESHOLD)
86 {
87 ret = 0;
88 if (++crying_counter >= LIMIT)
89 {
90 crying_counter = 0;
91 ret = 1;
92 }
93 return ret;
94 }
95
96 if (crying_counter > 0)
97 crying_counter--;
98
99 return 0;
100}
int processAudio(double *loudness)
Processes the audio to check whether the baby is crying.
Definition: microphone.c:73
double calculateLoudness()
Calculates loudness of the .wav file.
Definition: microphone.c:41
int startRecording()
Records a 2 second .wav audio from microphone.
Definition: microphone.c:18
#define ERR_OPEN
Definition: microphone.h:13
#define ERR_READ
Definition: microphone.h:14