繁体   English   中英

Visual C#中的逻辑循环

[英]Logical LOOP in Visual C#

我正在编写一个小型音乐应用程序,并以此方式每隔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,如果陈述,唯一的变化是:“ nutka”的名称和播放文件名的最后一位

(例如,在这里我们可以根据速度使用5个文件来播放一个音符“ A0”:-12dB_01,-9dB_01,-6dB_01,-3dB_01和0dB_01,这对于88个音符的代码来说确实很糟糕...

不知道如何制作短版或短循环……不胜感激。

通常,您可以通过提供一个描述您的功能的项目列表来做到这一点。

例如,给定一个简单的类

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" },

};

然后,您可以简单地根据nutkamsg.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);

也许您可以将字符串隐藏起来:

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);

字典的填充一次即可完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM