我想在 Windows 8 Metro 风格的应用程序中播放 mp3 文件中的声音.我尝试了两种方法来做到这一点:
I want to play sound from a mp3 file in windows 8 metro-style app. I tried two approaches to do so:
方法一:这是使用 stackoverflow/a/10961201/147530 提供的代码.它有效.
Method1: This is using the code provided by stackoverflow/a/10961201/147530. It works.
方法二:在这里,我只是新建了一个 MediaElement 并像这样设置它的 Source 属性:
Method 2: Here I just new a MediaElement and set its Source property like so:
var x = new MediaElement { Source = new Uri("ms-appx:/Assets/MyMp3File.mp3") };当我执行 x.Play() 时,什么也没有发生.没有抛出异常.
When I do x.Play() nothing happens however. There are no exceptions thrown.
问题:如何使方法 2 起作用?
Question: How can I make method 2 work?
想要更新没有使用方法 2 调用 MediaFailed、MediaOpened、MediaEnded 事件处理程序.
Wanted to update that none of the MediaFailed, MediaOpened, MediaEnded event handlers get called using Method 2.
sound = new MediaElement { Source = new Uri("ms-appx:/Assets/Clook.mp3") }; sound.MediaFailed += sound_MediaFailed; sound.MediaOpened += sound_MediaOpened; sound.MediaEnded += sound_MediaEnded; static void sound_MediaEnded(object sender, RoutedEventArgs e) { Debugger.Break(); } static void sound_MediaOpened(object sender, RoutedEventArgs e) { Debugger.Break(); } static void sound_MediaFailed(object sender, ExceptionRoutedEventArgs e) { Debugger.Break(); } 推荐答案可以尝试一些事情.试试下面的代码
A couple of things to try. Try the following code
var music = new MediaElement() { AudioCategory = AudioCategory.ForegroundOnlyMedia, Source = new Uri(this.BaseUri, "Assets/MyMp3File.mp3") }; // This is really the only difference, adding it to the visual tree // LayoutRoot is the root of the visual tree, in the case, a grid in my XAML LayoutRoot.Children.Add(music); music.Play();将其添加到可视化树中可能是关键.在其上设置一个断点以确保您的 MediaElement 中有数据.
Adding it to the visual tree may be the key. Put a break point on that to make sure your MediaElement has data in it.
第二(实际上发生在我身上,这就是我提到它的原因),我正在开发具有扩展坞的//Build 的三星设备.当设备位于扩展坞中时,设备上的音频插孔和扬声器将被禁用.您必须将耳机直接插入扩展坞或将其从扩展坞上取下才能听到任何声音.
Second (and actually happened to me so, that's why I mention it), I was developing on a Samsung device from //Build that has a docking station. The audio jack on the device and the speakers are disabled when it is in the docking station. You have to plug a headset into the docking station directly or remove it from the docking station to hear any sound.
更多推荐
无法在 Windows 8 中播放声音
发布评论