#include <SPI.h>
#include <SD.h>

// กำหนด pin
const int speakerPin = 9;
const int sdCardChipSelectPin = 10;

// ตัวแปร
File fileA, fileB, fileC, fileD;
bool isPlayingA = false, isPlayingB = false, isPlayingC = false, isPlayingD = false;

void setup() {
  // Serial.begin(9600);
  pinMode(speakerPin, OUTPUT);
  
  // Init SD card
  SPI.begin(13, 12, 11);
  SD.begin(sdCardChipSelectPin);
  
  // เปิดไฟล์เสียง
  fileA = SD.open("A.mp3");
  fileB = SD.open("B.mp3");
  fileC = SD.open("C.mp3");
  fileD = SD.open("D.mp3");
}

void loop() {
  // เล่นเสียงสตาร์ท
  if (!isPlayingA) {
    isPlayingA = true;
    fileA.seek(0);
    playFile(fileA);
  }
  
  // เล่นเสียงออกตัว
  if (isPlayingA && fileA.available() == 0) {
    isPlayingA = false;
    isPlayingB = true;
    fileB.seek(0);
    playFile(fileB);
  }
  
  // เล่นเสียงรถวิ่งคงที่
  if (isPlayingB && fileB.available() == 0) {
    isPlayingB = false;
    isPlayingC = true;
    fileC.seek(0);
    playFile(fileC);
  }
  
  // เล่นเสียงเครื่องยนต์เดินเบา
  if (isPlayingC && fileC.available() == 0) {
    isPlayingC = false;
    isPlayingD = true;
    fileD.seek(0);
    playFile(fileD);
  }
  
  // วนลูปเสียงเครื่องยนต์เดินเบา
  if (isPlayingD && fileD.available() == 0) {
    fileD.seek(0);
    playFile(fileD);
  }
}

void playFile(File file) {
  while (file.available()) {
    uint8_t data = file.read();
    analogWrite(speakerPin, data);
  }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: