|
| 1 | +#include <SD.h> |
| 2 | +#include <SPI.h> |
| 3 | +#include <Audio.h> |
| 4 | + |
| 5 | +void setup() |
| 6 | +{ |
| 7 | + // debug output at 115.2K |
| 8 | + Serial.begin(115200); |
| 9 | + |
| 10 | + // setup SD-card |
| 11 | + Serial.print("Initializing SD card..."); |
| 12 | + if (!SD.begin(4)) { |
| 13 | + Serial.println(" failed!"); |
| 14 | + return; |
| 15 | + } |
| 16 | + Serial.println(" done."); |
| 17 | + // hi-speed SPI transfers |
| 18 | + SPI.setClockDivider(4); |
| 19 | + |
| 20 | + // 44100Khz stereo => 88200 sample rate |
| 21 | + // 100 mSec of prebuffering. |
| 22 | + Audio.begin(88200, 100); |
| 23 | +} |
| 24 | + |
| 25 | +void loop() |
| 26 | +{ |
| 27 | + int count=0; |
| 28 | + |
| 29 | + // open wave file from sdcard |
| 30 | + File myFile = SD.open("fadh.wav"); |
| 31 | + if (!myFile) { |
| 32 | + // if the file didn't open, print an error and stop |
| 33 | + Serial.println("error opening fadh.wav"); |
| 34 | + while (true); |
| 35 | + } |
| 36 | + |
| 37 | + const int S=1024; // Number of samples to read in block |
| 38 | + int16_t buffer[S]; |
| 39 | + |
| 40 | + Serial.print("Playing"); |
| 41 | + // until the file is not finished |
| 42 | + while (myFile.available()) { |
| 43 | + // read from the file into buffer |
| 44 | + myFile.read(buffer, sizeof(buffer)); |
| 45 | + |
| 46 | + // Prepare samples |
| 47 | + int volume = analogRead(2); |
| 48 | + prepare(buffer, S, volume); |
| 49 | + // Feed samples to audio |
| 50 | + Audio.write(buffer, S); |
| 51 | + |
| 52 | + // Every 100 block print a '.' |
| 53 | + count++; |
| 54 | + if (count == 100) { |
| 55 | + Serial.print("."); |
| 56 | + count = 0; |
| 57 | + } |
| 58 | + } |
| 59 | + myFile.close(); |
| 60 | + |
| 61 | + |
| 62 | + Serial.println("End of file. Thank you for listening!"); |
| 63 | + while (true) ; |
| 64 | +} |
| 65 | + |
| 66 | + |
| 67 | +void prepare(int16_t *buffer, int S, int volume) { |
| 68 | + uint16_t *ubuffer = (uint16_t*) buffer; |
| 69 | + for (int i=0; i<S; i++) { |
| 70 | + // set volume amplitude (signed multiply) |
| 71 | + buffer[i] = buffer[i] * volume / 1024; |
| 72 | + // convert from signed 16 bit to unsigned 12 bit for DAC. |
| 73 | + ubuffer[i] += 0x8000; |
| 74 | + ubuffer[i] >>= 4; |
| 75 | + } |
| 76 | +} |
| 77 | + |
0 commit comments