好吧,您的“声音”将是一个值数组,无论是整数还是实数 - 取决于您的格式。
要使文件静音或“没有声音”,该数组中的值必须为零,或者非常接近零,或者最坏的情况 - 如果音频有偏差 - 值将保持不变左右波动产生声波。
您可以编写一个简单的函数来返回一个范围的增量,换句话说,最大值和最小值之间的差值,增量越小音量越低。
或者,您可以编写一个函数,返回差值低于给定阈值的范围。
为了玩,我写了一个漂亮的类:
template<typename T>
class SilenceFinder {
public:
SilenceFinder(T * data, uint size, uint samples) : sBegin(0), d(data), s(size), samp(samples), status(Undefined) {}
std::vector<std::pair<uint, uint>> find(const T threshold, const uint window) {
auto r = findSilence(d, s, threshold, window);
regionsToTime(r);
return r;
}
private:
enum Status {
Silent, Loud, Undefined
};
void toggleSilence(Status st, uint pos, std::vector<std::pair<uint, uint>> & res) {
if (st == Silent) {
if (status != Silent) sBegin = pos;
status = Silent;
}
else {
if (status == Silent) res.push_back(std::pair<uint, uint>(sBegin, pos));
status = Loud;
}
}
void end(Status st, uint pos, std::vector<std::pair<uint, uint>> & res) {
if ((status == Silent) && (st == Silent)) res.push_back(std::pair<uint, uint>(sBegin, pos));
}
static T delta(T * data, const uint window) {
T min = std::numeric_limits<T>::max(), max = std::numeric_limits<T>::min();
for (uint i = 0; i < window; ++i) {
T c = data[i];
if (c < min) min = c;
if (c > max) max = c;
}
return max - min;
}
std::vector<std::pair<uint, uint>> findSilence(T * data, const uint size, const T threshold, const uint win) {
std::vector<std::pair<uint, uint>> regions;
uint window = win;
uint pos = 0;
Status s = Undefined;
while ((pos + window) <= size) {
if (delta(data + pos, window) < threshold) s = Silent;
else s = Loud;
toggleSilence(s, pos, regions);
pos += window;
}
if (delta(data + pos, size - pos) < threshold) s = Silent;
else s = Loud;
end(s, pos, regions);
return regions;
}
void regionsToTime(std::vector<std::pair<uint, uint>> & regions) {
for (auto & r : regions) {
r.first /= samp;
r.second /= samp;
}
}
T * d;
uint sBegin, s, samp;
Status status;
};
我还没有真正测试过它,但它看起来应该可以工作。但是,它假设一个音频通道,您必须扩展它才能使用和跨多通道音频工作。以下是您的使用方法:
SilenceFinder<audioDataType> finder(audioDataPtr, sizeOfData, sampleRate);
auto res = finder.find(threshold, scanWindow);
// and output the silent regions
for (auto r : res) std::cout << r.first << " " << r.second << std::endl;
还要注意,现在的实现方式,“cut”到静默区域会非常突然,这种“noise gate”类型的过滤器通常带有攻击和释放参数,可以平滑结果。例如,可能有 5 秒的静音,中间只有一个微小的爆裂声,没有攻击和释放参数,你会得到 5 分钟一分为二,爆裂声实际上会保留,但是使用这些你可以实现不同的灵敏度什么时候剪掉。