【发布时间】:2014-07-27 22:30:33
【问题描述】:
我目前正在研究一种将 PCM 样本作为ICollection<dynamic> 接受的放大方法(调用者只会传递以下任一集合:sbyte、short 或 int)。我创建的放大算法运行良好;只是我不确定如何将新放大的样本转换回其原始类型,因为放大逻辑将样本输出为List<double>。
我知道我可以添加某种switch 语句来将样本转换回它们的原始类型,但这似乎是一个相当原始的解决方案,有没有更好的方法来完成这个?
我如何调用该方法(samples 是 List<dynamic> 延续 ints,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;
}
【问题讨论】:
-
你可以让这个方法通用,不是吗?
-
@ToughCoder 我没想过使用泛型,是的,我想这可以解决问题。谢谢。你想写一个答案,这样我就可以给你荣誉了吗?
-
很高兴为您提供帮助。感谢您的信任。
标签: c# .net variables dynamic casting