-
Notifications
You must be signed in to change notification settings - Fork 0
/
MusicPlayer.cpp
72 lines (58 loc) · 1.46 KB
/
MusicPlayer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "Particle.h";
#include "pitches.h";
#include "definitions.h";
#include "MusicPlayer.h";
MusicPlayer::MusicPlayer() {
timer = new Timer(1000, &MusicPlayer::endNote, *this);
noteInProgress = false;
tuneInProgress = false;
}
bool MusicPlayer::playInProgress() {
return tuneInProgress;
}
void MusicPlayer::playTune(String tuneId) {
if(noteInProgress) {
return;
}
if(tuneId == "win") {
melodyIndex = 0;
} else if(tuneId == "live") {
melodyIndex = 1;
} else if(tuneId == "lose") {
melodyIndex = 2;
}
noteIndex = 0;
tuneInProgress = true;
noteInProgress = false;
}
void MusicPlayer::tick() {
if(noteInProgress || !tuneInProgress) {
return;
}
int note = notes[melodyIndex][noteIndex];
int duration = 1000 / noteDurations[melodyIndex][noteIndex];
this->playNote(note, duration);
}
void MusicPlayer::playNote(int note, int duration) {
noteInProgress = true;
Log.trace("Start Note");
// Note!! This is non-blocking! The tone is automatically stopped by an interrupt.
tone(SPEAKER_PIN, note, duration);
// Include a pause of the length of the note
int durationWithRest = duration * 2;
timer->changePeriod(durationWithRest);
timer->reset();
}
void MusicPlayer::endNote() {
timer->stop();
Log.trace("End Note");
noteInProgress = false;
noteIndex++;
if(noteIndex >= noteCounts[melodyIndex]) {
this->endPlay();
}
}
void MusicPlayer::endPlay() {
noteInProgress = false;
tuneInProgress = false;
}