2016-04-27 122 views
0

我很書面方式小樂的應用程序和我玩每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」的名稱和播放文件名稱中的最後一位數字

(例如,在這裏我們可以使用一個音符「A0」 5個文件取決於速度:-12dB_01,-9dB_01,-6dB_01,-3dB_01和0dB_01,這看起來真的很糟糕的代碼爲88音符...

不知道如何使短版或短循環。 ..任何幫助apprreciated。

+0

列表和和一些lamdas將成爲你的朋友在這裏! – Sean

+0

如果'nutka ==「A1」'或'nutka ==「B4」'會怎麼樣?你能*計算最終的字符串嗎? –

回答

2

也許你可以concatinate字符串:

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

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

+0

謝謝:謝謝,我會測試它! :) – Martin

+0

謝謝!它完美的工作!你是英雄! :))) – Martin

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

}; 

然後,您可以簡單地查找正確的記錄基礎上,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); 
+0

謝謝Jamiec它看起來是最好的方式,使其工作,看起來「更短」:) 穆罕默德Zeeshan - 這種方式我需要再做出每個音符A0,A1,B0,B1的另外87個聲明.... ... – Martin