我目前正在研究一种放大方法,该方法接受 PCM 样本作为 ICollection<dynamic>
(调用者只会传递以下任一集合: sbyte
、 short
或 int
)。我创建的放大算法运行良好;只是我不确定如何将新放大的样本转换回其原始类型,因为放大逻辑将样本输出为 List<double>
.
我知道我可以添加某种 switch
声明将样本转换回原始类型,但这似乎是一个相当原始的解决方案,是否有更好的方法来完成此操作?
我如何调用该方法( samples
是 List<dynamic>
继续 int
s, file
是我为读取 wav 文件而创建的类),
AmplifyPCM(samples, file.BitDepth, 0.5f);
我的方法
static private List<dynamic> AmplifyPCM(ICollection<dynamic> samples, ushort bitDepth, float volumePercent)
{
var highestSample = 0;
var temp = new List<dynamic>();
foreach (var sample in samples)
{
if (sample < 0)
{
temp.Add(-sample);
}
else
{
temp.Add(sample);
}
}
foreach (var sample in temp)
{
if (sample > highestSample)
{
highestSample = sample;
}
}
temp = null;
var ratio = (volumePercent * (Math.Pow(2, bitDepth) / 2)) / highestSample;
var newSamples = new List<dynamic>();
foreach (var sample in samples)
{
newSamples.Add(sample * ratio); // ratio is of type double, therefore implicit conversion from whatever sample's type is to a double.
}
// switch statement would go here if there's no better way.
return newSamples;
}
最佳答案
好吧,您可以将其设为通用,从而给出返回类型。但 C# 不支持泛型运算符。您可以尝试将它们设置为动态。
static private List<T> AmplifyPCM<T>(ICollection<T> samples, ushort bitDepth, float volumePercent)
{
var highestSample = 0;
var temp = new List<T>();
foreach (var sample in samples)
{
if ((dynamic)sample < 0)
{
temp.Add(-(dynamic)sample);
}
else
{
temp.Add(sample);
}
}
foreach (var sample in temp)
{
if ((dynamic)sample > highestSample)
{
highestSample = (dynamic)sample;
}
}
temp = null;
var ratio = (volumePercent * (Math.Pow(2, bitDepth) / 2)) / highestSample;
var newSamples = new List<T>();
foreach (var sample in samples)
{
newSamples.Add((dynamic)(T)sample * ratio);
}
return newSamples;
}
关于c# - 如何将变量转换为与动态变量相同的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24085456/