-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathSimpleSound.cpp
More file actions
158 lines (128 loc) · 4.81 KB
/
Copy pathSimpleSound.cpp
File metadata and controls
158 lines (128 loc) · 4.81 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include "SimpleSound.h"
#include "Logger.h"
#include <fstream>
#include <random>
#include <windows.h>
#include <mmeapi.h>
#pragma comment(lib, "winmm.lib")
namespace fs = std::filesystem;
SimpleSound::SimpleSound(const unsigned char* data, unsigned int size) {
if (!loadFromBuffer(tempDefaultFile_, data, size)) {
Logger::logWarning("Failed to load sound from buffer (size: " + std::to_string(size) + ")");
throw std::runtime_error("Failed to load sound from buffer");
}
}
SimpleSound::~SimpleSound() {
if (!tempDefaultFile_.empty()) {
removeTempFile(tempDefaultFile_);
}
}
void SimpleSound::setVolume(int volume) noexcept {
if (volume < 0) volume = 0;
if (volume > 100) volume = 100;
volume_ = volume / 100.0f;
DWORD vol = static_cast<DWORD>(volume_ * 0xFFFF);
waveOutSetVolume(NULL, (vol << 16) | vol);
}
void SimpleSound::play() {
std::wstring filePath = tempSecondFile_.empty() ? tempDefaultFile_ : tempSecondFile_;
playRequests_.emplace_front(std::async(std::launch::async, [filePath, volume = volume_, tempDefaultFile = tempDefaultFile_]() {
std::wstring alias = generateAlias();
if (mciSendStringW((L"open \"" + filePath + L"\" type waveaudio alias " + alias).c_str(), NULL, 0, NULL) != 0) {
if (mciSendStringW((L"open \"" + tempDefaultFile + L"\" type waveaudio alias " + alias).c_str(), NULL, 0, NULL) != 0) {
Logger::logWarning("Failed to open WAV file");
return;
}
}
if (mciSendStringW((L"play " + alias + L" wait").c_str(), NULL, 0, NULL) != 0) {
Logger::logWarning("Failed to play WAV");
mciSendStringW((L"close " + alias).c_str(), NULL, 0, NULL);
return;
}
mciSendStringW((L"close " + alias).c_str(), NULL, 0, NULL);
}));
}
bool SimpleSound::secondBuffer(const std::string& filePath) {
if (!tempSecondFile_.empty()) {
tempSecondFile_.clear();
}
bool fileExists = fs::exists(filePath);
if (fileExists) {
tempSecondFile_ = std::wstring(filePath.begin(), filePath.end());
}
else {
fileExists = fs::exists(filePath + ".WAV");
if (fileExists) {
tempSecondFile_ = std::format(L"{}.WAV", std::wstring(filePath.begin(), filePath.end())).c_str();
}
}
return fileExists;
}
bool SimpleSound::loadFromBuffer(std::wstring &tempFile, const unsigned char* data, unsigned int size) {
if (!data || size == 0) {
Logger::logWarning("Invalid buffer: null or zero size");
return false;
}
std::ostringstream oss;
oss << std::hex << std::setfill('0');
for (unsigned int i = 0; i < (std::min)(size, 16u); ++i) {
oss << std::setw(2) << static_cast<unsigned>(data[i]) << " ";
}
tempFile = createTempFile(data, size);
return !tempFile.empty();
}
std::wstring SimpleSound::createTempFile(const unsigned char* data, unsigned int size) {
wchar_t tempPath[MAX_PATH];
wchar_t tempFile[MAX_PATH];
if (GetTempPathW(MAX_PATH, tempPath) == 0 || GetTempFileNameW(tempPath, L"WAV", 0, tempFile) == 0) {
Logger::logWarning("Failed to create temporary file path");
return L"";
}
std::ofstream file(tempFile, std::ios::binary);
if (!file.is_open()) {
Logger::logWarning("Failed to open temporary file for writing");
return L"";
}
file.write(reinterpret_cast<const char*>(data), size);
if (!file.good()) {
Logger::logWarning("Failed to write to temporary file");
file.close();
removeTempFile(tempDefaultFile_);
return L"";
}
file.close();
return std::wstring(tempFile);
}
bool SimpleSound::removeTempFile(std::wstring& tempFile) {
auto startTime = std::chrono::steady_clock::now();
const auto timeout = std::chrono::seconds(3);
while (fs::exists(tempFile)) {
try {
fs::permissions(tempFile, fs::perms::all, fs::perm_options::remove);
// Attempt to remove the file
if (fs::remove(tempFile)) {
return true;
}
}
catch (...) {}
// Check if 3 seconds have passed
if (std::chrono::steady_clock::now() - startTime >= timeout) {
Logger::logWarning("Failed to remove file within 3 seconds.");
break;
}
// Wait a bit before retrying
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
return false;
}
std::wstring SimpleSound::generateAlias() {
const std::wstring chars = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, chars.size() - 1);
std::wstring alias(8, L'\0');
for (int i = 0; i < 8; ++i) {
alias[i] = chars[dis(gen)];
}
return alias;
}