• WPF中播放声音


    1. 播放系统自带声音

      在System.Media命名空间中

      SystemSounds.Asterisk.Play();
      SystemSounds.Beep.Play();
      SystemSounds.Exclamation.Play();
      SystemSounds.Hand.Play();
      SystemSounds.Question.Play();
      
    2. 使用SoundPlayer播放.wav格式的声音

      1)仅支持.wav音频文件

      2)不支持同时播放多个音频

      3)无法控制声音的音量

      4)支持同步、异步播放

      5)支持循环播放

      6)支持文件和流播放

      下面是示例:

      SoundPlayer player = new SoundPlayer("test.wav");
      player.Play();
      
    3. 使用MediaPlayer播放声音

      这个是基于Windows Media Player构建的,因此支持Windows Media Player能播放的格式。

      1)可以同时播放多个声音

      2)可以调整音量(Volume属性)

      3)可以设置IsMuted属性实现静音

      4)可以通过NaturalDuration属性得到音频的藏毒,通过Position属性得到当前播放进度

      MediaPlayer player = new MediaPlayer();
      player.Open(new Uri("test.mp3", UriKind.Relative));
      player.Play();
      
    4. 使用MediaElement播放声音

      <MediaElement Source="test.mp3" LoadedBehavior="Play"/>
      
    5. 使用mciSendString系统播放音乐

      /// <summary>
          /// 音乐播放
          /// </summary>
          public static class AudioUtil
          {
              [DllImport("winmm.dll")]
              public static extern uint mciSendString(string lpstrCommand,
             string lpstrReturnString, uint uReturnLength, IntPtr hWndCallback);
              public static uint Play(string fileName)
              {
                  //mciSendString(@"close media", null, 0, IntPtr.Zero);
                  mciSendString($@"open ""{fileName}"" type mpegvideo alias media", null, 0, IntPtr.Zero);
                  return mciSendString("play media repeat", null, 0, IntPtr.Zero);
              }
              public static uint Stop()
              {
                  return mciSendString("close media", null, 0, IntPtr.Zero);
              }
          }
      

      其中media是别名,是在open命令时使用alias指定的别名,后面停止播放时要带上这个别名。

    6. 使用NAudio第三方库播放声音

      NuGet安装NAudio

      NAudio.Wave.Mp3FileReader mp3File = new NAudio.Wave.Mp3FileReader("test.mp3");//加载音频文件
      NAudio.Wave.WaveOut waveOut = new NAudio.Wave.WaveOut();
      waveOut.Init(mp3File);//初始化音频文件
      waveOut.Play();
      
    7. 使用Speech文字转音频播放声音

      需要添加引用System.Speech

      using (SpeechSynthesizer speech = new SpeechSynthesizer())
      {
          speech.Rate = 0;
          speech.Volume = 100;
          speech.Speak("你好啊");
      }
      
  • 相关阅读:
    007_在线解析json工具
    009_python魔法函数
    008_python列表的传值与传址
    008_python内置语法
    007_Python中的__init__,__call__,__new__
    006_Python 异常处理
    匹配网络设计
    Bessel函数
    system generator 卷积编码器快速设计
    关于非稳恒的电流激励电场
  • 原文地址:https://www.cnblogs.com/zzr-stdio/p/12758877.html
Copyright © 2020-2023  润新知