-
Notifications
You must be signed in to change notification settings - Fork 0
/
AudioVisualizer.cpp
79 lines (65 loc) · 2.47 KB
/
AudioVisualizer.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
/*
* Copyright (c) 2019 Rayé Maxime
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "AudioVisualizer.hpp"
void AudioVisualizer::_smoothArray(decltype(_scaleList) &data)
{
for (auto it = data.begin(); it != data.end(); ++it) {
if (it == data.begin())
*it = (*it + *(it + 1)) / 2.0;
else if (it == (data.end() - 1))
*it = (*it + *(it - 1)) / 2.0;
else
*it = (*(it - 1) + *it + *(it + 1)) / 3.0;
}
}
AudioVisualizer::AudioVisualizer(decltype(_sound) sound, decltype(_buffer) buffer)
: _sound{sound}, _buffer{buffer},
_bufferData{_buffer.getChannelCount(), _buffer.getSampleCount(),
_buffer.getSampleRate() * _buffer.getChannelCount()}
{
_array.resize(BUFFER_SIZE);
}
void AudioVisualizer::_fastFourierTransform(decltype(_array) &array)
{
const auto size = array.size();
if (size < 2)
return;
auto even = decltype(_array)(array[std::slice(0, size / 2, 2)]);
auto odd = decltype(_array)(array[std::slice(1, size / 2, 2)]);
_fastFourierTransform(even);
_fastFourierTransform(odd);
for (decltype(array.size()) i = 0; i < size / 2; ++i) {
Complex comp = std::polar(1.0, -2 * M_PI * i / size) * odd[i];
array[i] = even[i] + comp;
array[i + size / 2] = even[i] - comp;
}
}
AudioVisualizer::VisualizationData AudioVisualizer::getVisualizationData()
{
const auto position = static_cast<size_t>(_sound.getPlayingOffset().asSeconds() * _bufferData.sampleRate);
for (auto i = position; i - position < BUFFER_SIZE && i < _bufferData.sampleCount; ++i)
_array[i - position] = Complex(_buffer.getSamples()[i], 0.0);
_fastFourierTransform(_array);
double sum = 0;
size_t index = 0;
for (auto &value : _array) {
const auto abs = std::abs(value) / FREQ_MAX;
sum += abs;
_scaleList[index++] = abs;
}
_smoothArray(_scaleList);
return VisualizationData{sum / _array.size(), &_scaleList};
}