-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomAudioStream.cpp
More file actions
95 lines (71 loc) · 2.52 KB
/
CustomAudioStream.cpp
File metadata and controls
95 lines (71 loc) · 2.52 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
#include "CustomAudioStream.h"
CustomAudioStream::CustomAudioStream() {
initialize(channelCount, sampleRate);
}
bool CustomAudioStream::loadFromFile(const std::string& filename) {
sf::SoundBuffer buffer;
if (!buffer.loadFromFile(filename)) {
std::cerr << "Failed to load file: " << filename << std::endl;
return false;
}
samples.assign(buffer.getSamples(), buffer.getSamples() + buffer.getSampleCount());
sampleRate = buffer.getSampleRate();
channelCount = buffer.getChannelCount();
initialize(channelCount, sampleRate);
dt = 1.0f / static_cast<float>(sampleRate);
RC_low = 1.0f / (2 * 3.1416f * lowCutoff);
RC_high = 1.0f / (2 * 3.1416f * highCutoff);
alphaLow = dt / (RC_low + dt);
alphaHigh = RC_high / (RC_high + dt);
currentSample = 0;
return true;
}
void CustomAudioStream::setVolume(float vol) {
volume = vol;
}
void CustomAudioStream::setEqualizerGains(float low, float mid, float high) {
lowGain = low;
midGain = mid;
highGain = high;
}
bool CustomAudioStream::onGetData(Chunk& data) {
const std::size_t chunkSize = 4096;
if (currentSample >= samples.size())
return false;
std::size_t endSample = std::min(currentSample + chunkSize, samples.size());
buffer.resize(endSample - currentSample);
for (std::size_t i = 0; i < buffer.size(); ++i) {
buffer[i] = applyEqualizer(samples[currentSample + i]);
}
data.samples = buffer.data();
data.sampleCount = buffer.size();
currentSample = endSample;
return true;
}
void CustomAudioStream::onSeek(sf::Time timeOffset) {
currentSample = static_cast<std::size_t>(timeOffset.asSeconds() * sampleRate * channelCount);
}
sf::Int16 CustomAudioStream::applyEqualizer(sf::Int16 sample) {
//Limiter
float totalGain = lowGain + midGain + highGain;
if (totalGain > 3.0f) {
float scale = 3.0f / totalGain;
lowGain *= scale;
midGain *= scale;
highGain *= scale;
}
float s = static_cast<float>(sample);
// Low-pass filter (íèçêèå ÷àñòîòû)
lowY = lowY + alphaLow * (s - lowY);
float low = lowY;
// High-pass filter (âûñîêèå ÷àñòîòû)
highY = alphaHigh * (highY + s - prevInput);
prevInput = s;
float high = highY;
// Middle = îðèãèíàë - (low + high)
float mid = s - (low + high);
// Óñèëåíèå êàæäîé ïîëîñû
float result = low * lowGain + mid * midGain + high * highGain;
result *= volume / 100.f;
return static_cast<sf::Int16>(std::clamp(result, -32768.f, 32767.f));
}