Play a wav clip in the headphones (or a speaker)

Dependencies:   mbed

Revision:
0:17458f91a0e9
Child:
1:91104d67b0af
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/talking.cpp	Sun Feb 05 09:52:10 2017 +0000
@@ -0,0 +1,77 @@
+#include "mbed.h"
+
+Ticker rhythm;
+LocalFileSystem fs("local");  // required even if it appears like it's not used
+
+DigitalIn button(p20);
+DigitalOut led(LED1);
+AnalogOut headphones(p18);
+
+void myrhythm();
+void waitForButton(DigitalOut& led, DigitalIn& button);
+void preloadFile(char* clip, int size, const char* path);
+void playSound(char* clip, int size, AnalogOut& headphones);
+
+enum
+{
+    OFF = 0,
+    ON = 1
+};
+
+enum { MaxWavValue = 255 };
+
+static const float ticker_rhythm = 13E-5;  // 8 kHz sample rate (1/8000 sec delay)
+static const char clip_path[] = "/local/blonde.wav";
+
+
+bool done = false;
+
+
+void myrhythm()
+{
+    done = true;
+}
+
+int main () 
+{
+    const int size = 30000;   // 32K max in total (~30K is enough for testing)
+    char clip[size];
+    
+    waitForButton(led, button);
+    preloadFile(clip, size, clip_path);
+    
+    rhythm.attach(&myrhythm, ticker_rhythm);
+    
+    while (true)
+    {        
+        waitForButton(led, button);        
+        playSound(clip, size, headphones);
+    }
+}
+
+void waitForButton(DigitalOut& led, DigitalIn& button)
+{
+  led = ON;
+  while (!button) {};
+  led = OFF;
+}
+
+void preloadFile(char* clip, int size, const char* path)
+{
+  FILE* file = fopen(path, "r");
+  for (int i = 0; i != size; ++i)
+    {
+      clip[i] = fgetc(file);
+    }
+  fclose(file);
+}
+
+void playSound(char* clip, int size, AnalogOut& headphones)
+{
+    for (int i= 0; i != size; ++i) 
+    {
+        while (!done) {};
+        done = false;
+        headphones = float(clip[i]) / MaxWavValue;
+    }
+}