简体   繁体   English

在 C# 中的 Combobox 中播放声音

[英]Play sound in Combobox in C#

I'm new in C# programming, I created a combobox with items and I want that items to play sound when i chose one, like this , or that.我是 C# 编程的新手,我创建了一个包含项目的组合框,我希望这些项目在我选择一个时播放声音,比如这个或者那个。

I'm using Visual Studio 2015.我正在使用 Visual Studio 2015。

Could would be in methods play1 and play2可能会在方法 play1 和 play2 中

private void AudioComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (AudioComboBox.SelectedIndex == AudioComboBox.Items.IndexOf("Sali 3la Mohammed 1"))
            {
                play1();
            }

            else if (AudioComboBox.SelectedIndex == AudioComboBox.Items.IndexOf("Sali 3la Mohammed 2"))
            {
                play2();
            }
        }


        private void play1()
        {
        }
        private void play2()
        {  
        }

You can use MediaElement or the new AudioGraph to play sounds in UWP.你可以使用MediaElement或新的AudioGraph在 UWP 中播放声音。

MediaElement is the simpler approach, which has the disadvantage of causing the music stop on Mobile devices, so it is really not too appropriate your purpose. MediaElement是更简单的方法,它的缺点是会导致移动设备上的音乐停止,因此它确实不太适合您的目的。

MediaElement player = new MediaElement();
var stream = await yourSoundFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
player.SetSource(stream, file.ContentType);
player.Play();

AudioGraph is specifically created for sound effects in UWP apps and is the best choice for you. AudioGraph专为 UWP 应用中的音效而创建,是您的最佳选择。 There is a quick and simple tutorial on Loek van den Ouweland's blog , so I definitely recommend you to check it out. Loek van den Ouweland 的博客上有一个快速简单的教程,所以我强烈建议您查看一下。 Basically you need to create an AudioGraph instance and with it AudioFileInputNode s for each of the sounds you need.基本上,您需要创建一个AudioGraph实例,并使用它为您需要的每个声音创建AudioFileInputNode

This should work这应该工作

private void AudioComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (AudioComboBox.SelectedIndex == AudioComboBox.Items.IndexOf("Sali 3la Mohammed 1"))
            {
                play1();
            }

            else if (AudioComboBox.SelectedIndex == AudioComboBox.Items.IndexOf("Sali 3la Mohammed 2"))
            {
                play2();
            }
        }


        private void play1()
        {
            SoundPlayer simpleSound = new SoundPlayer("sound1.wav");
            simpleSound.Play();
        }
        private void play2()
        {  
            SoundPlayer simpleSound = new SoundPlayer("sound2.wav");
            simpleSound.Play();
        }

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

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