我尝试从按钮事件处理程序播放声音:
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();
}
}
}
但是我收到一个错误,其中类型或命名空间“media”在命名空间“system”中不存在。似乎是什么问题?
我使用的是 visual studio 2017,我创建了一个通用的 Windows c# 空白应用程序。
编辑:
我已将我的代码更改为此,但我仍然无法播放任何音频。
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();
}
}
}
我已经尝试添加背景声明以允许背景音频,但仍然无济于事。
最佳答案
您正在使用 .Net Core 并且 System.Media 在 .Net Framework 中。
在 .Net Core 中,您可以使用 Windows.UI.Xaml.Controls.MediaElement。或者,您可以使用 Windows.Media.Audio.AudioGraph。
关于c# - 按下按钮时在 C# 中播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43570187/