如何沿着莫尔斯电码字母播放声音效果

问题描述

所以我在C#visual studio中编写一个摩尔斯电码翻译器,它接受输入文本,然后将其作为摩尔斯电码保存到文本文件中。但是,我试图编写代码来播放每个字母的声音,为此我在Visual Studio项目中为每个字母都提供了.wav文件。在此代码中,我有一个将英语字母单词与各自的摩尔斯电码字母匹配的翻译器,我正在尝试使相应的.wav文件与翻译后的字母一起播放。

代码如下:

private static void InitializeDictionary()
{
    _morseAlphabetDictionary = new Dictionary<char,string>()
                               {
                                   {'a',".-"},Soundplayer snd = new Soundplayer(@"C:\Users\keife\source\repos\MorseCodeTranslator\MorseCodeTranslator\AnyConv.com__A_morse_code.wav");
    snd.Play();
    { 'b',"-..."},{'c',"-.-."},{'d',"-.."},{'e',"."},{'f',"..-."},{'g',"--."},{'h',"...."},{'i',".."},{'j',".---"},{'k',"-.-"},{'l',".-.."},{'m',"--"},{'n',"-."},{'o',"---"},{'p',".--."},{'q',"--.-"},{'r',".-."},{'s',"..."},{'t',"-"},{'u',"..-"},{'v',"...-"},{'w',".--"},{'x',"-..-"},{'y',"-.--"},{'z',"--.."},{'0',"-----"},{'1',".----"},{'2',"..---"},{'3',"...--"},{'4',"....-"},{'5',"....."},{'6',"-...."},{'7',"--..."},{'8',"---.."},{'9',"----."}
                               };
}

但是,代码生成错误

'Soundplayer'是一种类型,在给定的上下文中无效

任何建议如何正确格式化?非常感谢。

修改后的代码

     {'a',new MorseMapping(".-",@"C:\Users\keife\source\repos\MorseCodeTranslator\MorseCodeTranslator\AnyConv.com__A_morse_code.wav")},_morseAlphabetDictionary['a'].Player.Play();

   

解决方法

您正在尝试创建SoundPlayer并将其插入字典的初始化块中。这就是为什么会出现错误的原因,因为字典中期望有一个char-string对。将其放在字典的声明之前:

SoundPlayer snd = new SoundPlayer(@"C:\Users\keife\source\repos\MorseCodeTranslator\MorseCodeTranslator\AnyConv.com__A_morse_code.wav");
_morseAlphabetDictionary = new Dictionary<char,string>()
                           {
                               {'a',".-"},

第二件事是,我建议您不仅映射莫尔斯电文字母,而且已经映射到相应的wav文件或enudre soudnplayer的路径。您可以为其使用自定义类

public class MorseMapping
{
    public string MorseLetter {get; set;}
    public SoundPlayer Player {get; set;}

    public MorseMapping(string letter,string filePath)
    {
         this.MorseLetter = letter;
         this.Player = new SoundPlayer(filePath):
    }
}

现在您可以在字典中使用此类:

_morseAlphabetDictionary = new Dictionary<char,MorseMapping>()
                           {
                               {'a',new MorseMapping(".-",@"C:\myPath\fileForA.wav")},//.. here goes  the rest
                           }; // end of initialization block!!!

现在,如果您想为a播放声音,请提取Mapping并使用声音播放器:

_morseAlphabetDictionary['a'].Player.Play();

编辑:非常重要!:在字典的初始化块之外调用播放器。除了字典项init之外,不要在初始化块中放置任何其他代码!

,

根据您在注释中显示的错误,您可以尝试以下代码来解决问题。

请不要在字典中调用方法href

代码:

Player.Play()