WPF 中播放音频

62 阅读1分钟

WPF 如何播放音效

WPF中播放音效的三种简单方式

  • MediaElement
  • MediaPlayer
  • SoundPlayer

样例代码

  • 项目结构

image.png

  • MainWindow.xmal
<Window x:Class="SoundPlayDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SoundPlayDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <MediaElement x:Name="soundPlay" Source="start_wb3.mp3" LoadedBehavior="Manual"/>
    </Grid>
</Window>

  • MainWindow.cs
using System.Media;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SoundPlayDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            _ = TestSounderPlay();
        }

        private async Task TestSounderPlay()
        {
            Console.WriteLine("play media by MediaElement");
            soundPlay.Play();

            await Task.Run(() =>
            {
                Thread.Sleep(3000);
                PlaySoundByMediaPlayer();
            });

            await Task.Run(() => {
                Thread.Sleep(3000);
                PlaySoundBySoundPlayer();
            });
          
        }

        private void PlaySoundByMediaPlayer()
        {
            Console.WriteLine("play media by MediaPlayer");
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.Open(new Uri("trap-beat-2-with-stems-140bpm-159341.mp3", UriKind.RelativeOrAbsolute));

            mediaPlayer.Play();
        }

        private void PlaySoundBySoundPlayer()
        {
            Console.WriteLine("play media by MediaPlayer");
            SoundPlayer soundPlayer = new SoundPlayer("不如不见.wav");
            soundPlayer.Play();
        }
    }
}