SimpleAudioPlayer.ino 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Simple Audio Player
  3. Demonstrates the use of the Audio library for the Arduino Due
  4. Hardware required :
  5. * Arduino shield with a SD card on CS4
  6. * A sound file named "test.wav" in the root directory of the SD card
  7. * An audio amplifier to connect to the DAC0 and ground
  8. * A speaker to connect to the audio amplifier
  9. Original by Massimo Banzi September 20, 2012
  10. Modified by Scott Fitzgerald October 19, 2012
  11. This example code is in the public domain
  12. http://www.arduino.cc/en/Tutorial/SimpleAudioPlayer
  13. */
  14. #include <SD.h>
  15. #include <SPI.h>
  16. #include <Audio.h>
  17. void setup() {
  18. // debug output at 9600 baud
  19. Serial.begin(9600);
  20. // setup SD-card
  21. Serial.print("Initializing SD card...");
  22. if (!SD.begin(4)) {
  23. Serial.println(" failed!");
  24. return;
  25. }
  26. Serial.println(" done.");
  27. // hi-speed SPI transfers
  28. SPI.setClockDivider(4);
  29. // 44100Khz stereo => 88200 sample rate
  30. // 100 mSec of prebuffering.
  31. Audio.begin(88200, 100);
  32. }
  33. void loop() {
  34. int count = 0;
  35. // open wave file from sdcard
  36. File myFile = SD.open("test.wav");
  37. if (!myFile) {
  38. // if the file didn't open, print an error and stop
  39. Serial.println("error opening test.wav");
  40. while (true);
  41. }
  42. const int S = 1024; // Number of samples to read in block
  43. short buffer[S];
  44. Serial.print("Playing");
  45. // until the file is not finished
  46. while (myFile.available()) {
  47. // read from the file into buffer
  48. myFile.read(buffer, sizeof(buffer));
  49. // Prepare samples
  50. int volume = 1024;
  51. Audio.prepare(buffer, S, volume);
  52. // Feed samples to audio
  53. Audio.write(buffer, S);
  54. // Every 100 block print a '.'
  55. count++;
  56. if (count == 100) {
  57. Serial.print(".");
  58. count = 0;
  59. }
  60. }
  61. myFile.close();
  62. Serial.println("End of file. Thank you for listening!");
  63. while (true) ;
  64. }