我试图从按钮事件处理程序中播放声音:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void mainButton_Click_1(object sender, RoutedEventArgs e)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav");
player.Play();
}
}
}
但我收到的错误是类型或命名空间&#34; media&#34;在名称空间&#34; system&#34;中不存在。什么似乎是问题?
我正在使用Visual Studio 2017,并且我已经创建了一个通用的Windows c#blank应用程序。
编辑:
我已将代码更改为此但我还没有收到任何音频播放。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void mainButton_Click_1(object sender, RoutedEventArgs e)
{
MediaElement PlayMusic = new MediaElement();
PlayMusic.AudioCategory = Windows.UI.Xaml.Media.AudioCategory.Media;
PlayMusic.Source = new Uri(@"D:/Downloads/sounds.mp3");
PlayMusic.Play();
}
}
}
我尝试添加背景声明以允许背景音频,但仍无济于事。
答案 0 :(得分:2)
您正在使用.Net Core和System.Media位于.Net Framework中。
在.Net Core中,您可以使用Windows.UI.Xaml.Controls.MediaElement。或者,您可以使用Windows.Media.Audio.AudioGraph。