#include <WiFi.h>
#include <SD.h>
#include <HTTPClient.h>
#include <Audio.h>
#include <time.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* serverUrl = "https://download.samplelib.com/mp3/sample-6s.mp3"; // URL of the music file
const int chipSelect = 5; // Chip select pin for SD card
void connectToWiFi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting...");
}
Serial.println("Connected to WiFi!");
}
void setup() {
Serial.begin(115200);
connectToWiFi();
// Initialize SD card
if (!SD.begin(chipSelect)) {
Serial.println("SD card initialization failed!");
return;
}
Serial.println("SD card initialized.");
// Fetch current time from NTP server
configTime(0, 0, "pool.ntp.org");
while (!time(nullptr)) {
delay(1000);
Serial.println("Waiting for time sync...");
}
Serial.println("Time synced.");
// Schedule music playback at a specific time
struct tm tm;
tm.tm_hour = 10; // Example: 8 AM
tm.tm_min = 0;
tm.tm_sec = 0;
tm.tm_year = 0;
tm.tm_mon = 0;
tm.tm_mday = 0;
time_t scheduledTime = mktime(&tm);
// Calculate time until scheduled playback
time_t currentTime = time(nullptr);
long delayTime = difftime(scheduledTime, currentTime);
if (delayTime < 0) {
// If scheduled time has already passed, add one day
delayTime += 86400;
}
// Delay until scheduled time
Serial.print("Waiting until scheduled time...");
delay(delayTime * 1000);
Serial.println("Time to play music!");
// Download music file
HTTPClient http;
http.begin(serverUrl);
int httpCode = http.GET();
if (httpCode > 0) {
File musicFile = SD.open("/music.mp3", FILE_WRITE);
if (musicFile) {
WiFiClient * stream = http.getStreamPtr();
while (stream->available()) {
musicFile.write(stream->read());
}
musicFile.close();
Serial.println("Music downloaded and saved to SD card.");
}
} else {
Serial.println("Failed to download music file.");
}
http.end();
// Play music
Audio.begin(0);
Audio.setVolume(0.5);
Audio.connecttoFS("/music.mp3");
Audio.loop();
}
void loop() {
// Nothing to do here since music is played in setup
}