-
Notifications
You must be signed in to change notification settings - Fork 2
/
soundplayer.cpp
92 lines (80 loc) · 2.76 KB
/
soundplayer.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "soundplayer.h"
#include <QFile>
#include <QTextStream>
#include <QTime>
void SoundPlayer::playFile(QString path, bool addToEndOfList) {
SoundPlayer *ip = instance();
if (addToEndOfList) ip->sounds_to_play.append(path);
else ip->sounds_to_play.prepend(path);
if (!ip->timer.isActive()) ip->update();
}
void SoundPlayer::clear() {
timer.stop();
sounds_to_play.clear();
}
void SoundPlayer::update() {
if (sounds_to_play.isEmpty()) return;
QString name = sounds_to_play.takeFirst();
qDebug() << "[SP] Playing " << base_path << name << ".wav. "
<< sounds_to_play.size() << " more in list.";
QSound::play(base_path + name + ".wav");
if (sound_lengths.contains(name))
timer.start(sound_lengths[name]*1000+1000);
else timer.start(2000);
}
SoundPlayer::SoundPlayer(QObject *parent): QObject(parent) {
#ifdef Q_OS_WIN32
base_path = "C:/Users/3r/coding/SolderingSkaters/C---Port/Resources/sounds/";
#else
base_path = "";
#endif
readLenghtsFromFile(":/sounds/lengths.txt");
timer.setSingleShot(true);
connect(&timer, SIGNAL(timeout()), this, SLOT(update()));
qsrand(QTime::currentTime().msec());
sounds_map["Ollie"] = QList<QString>();
sounds_map["Ollie"] << "m_trick_ollie" << "f_trick_ollie";
sounds_map["180"] = QList<QString>();
sounds_map["180"] << "f_trick_180";
for (int i=1; i<=7; i++) {
if (i <= 5) sounds_good << QString("m_good_0%1").arg(QString::number(i));
sounds_good << QString("f_good_0%1").arg(QString::number(i));
}
}
QString SoundPlayer::pickOne(QStringList list) {
if (list.size() < 1) return "";
return list[qrand() % list.size()];
}
void SoundPlayer::playTrick(QString trickid, bool praise_if_unknown) {
SoundPlayer* td = instance();
if (td->sounds_map.contains(trickid)) {
playFile(pickOne(td->sounds_map[trickid]));
} else if (praise_if_unknown) playPraise();
}
void SoundPlayer::playLevel(int i) {
if (i < 1 || i > 5) return;
playFile(QString("f_level%1").arg(QString::number(i)));
}
void SoundPlayer::playPraise() {
playFile(pickOne(instance()->sounds_good));
}
void SoundPlayer::readLenghtsFromFile(QString path) {
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Could not open '" << path << "' which should contain the sound lengths.";
return;
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
QString name = line.section(',', 0, 0);
int length = line.section(',', 1, 1).toInt();
if (name.size() > 0) sound_lengths.insert(name, length);
}
}
SoundPlayer* SoundPlayer::instance() {
static SoundPlayer* inst = 0;
if(!inst)
inst = new SoundPlayer;
return inst;
}