我正在写一个小型音乐应用程序,我用这种方式播放每88个键:
if (nutka == "A0" && msg.Velocity < 28)
{
PlayEngine.Instance.PlaySound("-12dB_01");
}
else if (nutka == "A0" && msg.Velocity < 55 && msg.Velocity > 27)
{
PlayEngine.Instance.PlaySound("-9dB_01");
}
else if (nutka == "A0" && msg.Velocity < 82 && msg.Velocity > 54)
{
PlayEngine.Instance.PlaySound("-6dB_01");
}
else if (nutka == "A0" && msg.Velocity < 106 && msg.Velocity > 81)
{
PlayEngine.Instance.PlaySound("-3dB_01");
}
else if (nutka == "A0" && msg.Velocity < 128 && msg.Velocity > 105)
{
PlayEngine.Instance.PlaySound("0dB_01");
}
如您所见,我有一个键的5个速度范围,用于来自我的外部midi控制器的信号。我有类似的88 if if statments,唯一变化的是:“nutka”的名字和播放文件名称的最后一位数
(例如,在这里我们可以通过使用5个文件来播放一个音符“A0”取决于速度:-12dB_01,-9dB_01,-6dB_01,-3dB_01和0dB_01,这在88个音符的代码中看起来真的很糟糕。 ..
不知道如何制作更短的版本或可能是短循环......任何帮助都会被评估。
答案 0 :(得分:2)
您通常会通过提供描述您的功能的项目列表来实现此目的。
例如,给定一个简单的类
public class SoundInfo
{
public string Nutka{get;set;}
public int MinVelocity {get;set;}
public int MaxVelocity {get;set;}
public string SoundFile{get;set;}
}
您将它们存储在List<SoundInfo>
public List<SoundInfo> sounds
= new List<SoundInfo>()
{
new SoundInfo { Nutka = "A0", MinVelocity = 0, MaxVelocity = 28, SoundFile="-12dB_01" },
new SoundInfo { Nutka = "A0", MinVelocity = 28, MaxVelocity = 55 SoundFile="-6dB_01" },
new SoundInfo { Nutka = "A0", MinVelocity = 55, MaxVelocity = 82, SoundFile="-3dB_01" },
};
然后,您可以根据nutka
和msg.Velocity
的值查找正确的记录:
var item = sounds.SingleOrDefault(s => s.Nutka == nutka
&& msg.Velocity < s.MaxVelocity && msg.Velocity >= s.MinVelocity);
if(item == null)
throw new Exception ("No sound found!!");
PlayEngine.Instance.PlaySound(item.SoundFile);
答案 1 :(得分:2)
也许你可以整理字符串:
var keys = new Dictionary<string, string>();
// fill dictionary with relations: A0 -> 01
keys.Add("A0", "01");
var key = keys[nutka];
int velocity;
if (msg.Velocity < 28)
velocity = -12
else if (msg.Velocity < 55)
velocity = -9
else if (msg.Velocity < 82)
velocity = -6
else if (msg.Velocity < 106)
velocity = -3
else
velocity = 0;
string tune = String.Format("{0}dB_{1}", velocity, key);
PlayEngine.Instance.PlaySound(tune);
填写字典可以完成一次。