首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在MediaPlayer中播放来自SpeechSynthesizer的wav文件

如何在MediaPlayer中播放来自SpeechSynthesizer的wav文件
EN

Stack Overflow用户
提问于 2018-09-09 20:22:03
回答 2查看 557关注 0票数 2

我有一些代码(在WPF应用程序中),当一些文本被复制到剪贴板时,它会使用SpeechSynthesizer读出文本(我的所有代码都在本文的底部)。

然而,以这种方式播放音频并不允许我暂停、倒带或播放等。

所以我想我应该用SpeechSynthesizer来保存一个wav文件。然后使用MediaPlayer类,因为它很容易暂停,播放等。

但是,在保存文件后,该文件不能在我的媒体播放器中播放。这个文件很好,当我手动运行它时,它工作得很好。我想使用MediaPlayer,因为我已经为它编写了一些代码。

更新

使用示例on this page,我可以播放wav文件。我不知道为什么这个文件不能在我的代码中运行?在上面的示例中,我知道他们使用的是Media元素,并在我的代码中尝试过,这没有什么不同。我不是在播放视频,而是在播放音频,所以我才会使用MediaPlayer。

这是我当前所有的代码。文件正在保存,但据我所知,媒体播放器没有播放任何内容,我电脑的音量调得很高。

     using System;
     using System.Windows;
     using System.Windows.Controls;
     using System.Windows.Media;
     using System.Windows.Media.Imaging;
     using System.Windows.Interop;
     using System.IO;
     using System.Speech.Synthesis;
     using System.Windows.Controls.Primitives;
     using System.Windows.Threading;

     namespace CSWPFClipboardViewer
     {
      /// <summary>
      /// Main window of the application, also will be used to get clipboard messages.
      /// </summary>
      public partial class MainWindow : Window
      {
        #region Private fields

        /// <summary>
        /// Next clipboard viewer window 
        /// </summary>
        private IntPtr hWndNextViewer;

        /// <summary>
        /// The <see cref="HwndSource"/> for this window.
        /// </summary>
        private HwndSource hWndSource;

        private bool isViewing;

        private MediaPlayer mePlayer = new MediaPlayer();

        #endregion

        public MainWindow()
        {
           InitializeComponent();
        }

        #region Clipboard viewer related methods

        private void InitCBViewer()
        {
            WindowInteropHelper wih = new WindowInteropHelper(this);
            hWndSource = HwndSource.FromHwnd(wih.Handle);

            hWndSource.AddHook(this.WinProc);   // start processing window messages
            hWndNextViewer = Win32.SetClipboardViewer(hWndSource.Handle);   // set this window as a viewer
            isViewing = true;
        }

        private void CloseCBViewer()
        {
            // remove this window from the clipboard viewer chain
           Win32.ChangeClipboardChain(hWndSource.Handle, hWndNextViewer);

           hWndNextViewer = IntPtr.Zero;
           hWndSource.RemoveHook(this.WinProc);
           pnlContent.Children.Clear();
           isViewing = false;
        }

        private void DrawContent()
        {
           pnlContent.Children.Clear();

           if (Clipboard.ContainsText())
           {
              string path = @"C:\Users\MyPath\";
              string fileName = "MyFile.wav";

              // delete previous file if it exists
              if (File.Exists(path + fileName))
                  File.Delete(path + fileName);

              // we have some text in the clipboard.
              TextBox tb = new TextBox();
              tb.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
              tb.FontSize = 24;
              tb.Text = Clipboard.GetText();
              tb.IsReadOnly = true;
              tb.TextWrapping = TextWrapping.Wrap;
              pnlContent.Children.Add(tb);

              SpeechSynthesizer synthesizer = new SpeechSynthesizer();
              synthesizer.Volume = 100;  // 0...100
              synthesizer.Rate = 3;     // -10...10

              //Asynchronous
              synthesizer.SetOutputToWaveFile(path + fileName);
              synthesizer.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synth_SpeakCompleted);
              synthesizer.SpeakAsync(Clipboard.GetText());


             }
            else
            {
               Label lb = new Label();
               lb.Content = "The type of the data in the clipboard is not supported by this sample.";
               pnlContent.Children.Add(lb);
            }
         }

    private IntPtr WinProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        switch (msg)
        {
            case Win32.WM_CHANGECBCHAIN:
                if (wParam == hWndNextViewer)
                {
                    // clipboard viewer chain changed, need to fix it.
                    hWndNextViewer = lParam;
                }
                else if (hWndNextViewer != IntPtr.Zero)
                {
                    // pass the message to the next viewer.
                    Win32.SendMessage(hWndNextViewer, msg, wParam, lParam);
                }
                break;

            case Win32.WM_DRAWCLIPBOARD:
                // clipboard content changed
                this.DrawContent();
                // pass the message to the next viewer.
                Win32.SendMessage(hWndNextViewer, msg, wParam, lParam);
                break;
        }

        return IntPtr.Zero;
    }

    #endregion

    #region Control event handlers

    void synth_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
    {
        string path = @"C:\Users\MyPath\";
        string fileName = "MyFile.wav";

        mePlayer.Open(new Uri(path + fileName));
        mePlayer.Play();
    }

    private void btnSwitch_Click(object sender, RoutedEventArgs e)
    {
        // switching between start/stop viewing state
        if (!isViewing)
        {
            this.InitCBViewer();
            btnSwitch.Content = "Stop viewer";
        }
        else
        {
            this.CloseCBViewer();
            btnSwitch.Content = "Start viewer";
        }
    }

    private void btnClose_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }

    private void Window_Closed(object sender, EventArgs e)
    {
        this.CloseCBViewer();
    }

    #endregion
    }
  }

C# Win32

    using System;
    using System.Runtime.InteropServices;

    namespace CSWPFClipboardViewer
    {
      /// <summary>
      /// This static class holds the Win32 function declarations and constants needed by
      /// this sample application.
      /// </summary>
      internal static class Win32
      {
         /// <summary>
         /// The WM_DRAWCLIPBOARD message notifies a clipboard viewer window that 
         /// the content of the clipboard has changed. 
         /// </summary>
         internal const int WM_DRAWCLIPBOARD = 0x0308;

         /// <summary>
         /// A clipboard viewer window receives the WM_CHANGECBCHAIN message when 
         /// another window is removing itself from the clipboard viewer chain.
         /// </summary>
    internal const int WM_CHANGECBCHAIN = 0x030D;

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
   }
 }

XAML

 <Window x:Class="CSWPFClipboardViewer.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"
Title="Clipboard Viewer" Height="500" Width="640" Background="Black" Closed="Window_Closed">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Label Grid.Row="0" Foreground="White" Margin="6,0,6,0">Clipboard content:</Label>

    <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right">
        <Button x:Name="btnSwitch" Width="90" Height="25" Content="Start viewer" Padding="3" Margin="6,6,6,6" Click="btnSwitch_Click" />
        <Button x:Name="btnClose" Width="90" Height="25" Content="Close" Padding="3" Margin="6,6,6,6" Click="btnClose_Click" />
    </StackPanel>

    <DockPanel x:Name="pnlContent" Grid.Row="1" Background="White" Margin="6,6,6,6" LastChildFill="True"/>
</Grid>

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-09 20:28:18

默认情况下,synthesizer.SpeakAsync将使用扬声器作为输出。您可以将输出设置为wave文件。如果您现在调用synthesizer.SpeakAsync,合成器将“对话”到wave文件,在本例中这意味着对其进行写入。所以synthesizer.SpeakAsync不会播放任何可听的声音。

有关更多指导信息,请参阅示例here

一旦创建了wav文件,您就可以使用媒体播放器打开它。

synthesizer.SpeakAsync("Youre text goes here");
var pathUri = new Uri(path);
player.Open(pathUri.AbsoluteUri);
票数 6
EN

Stack Overflow用户

发布于 2018-09-18 11:28:25

当我试图复制你的问题时,我发现了一些非常有趣的事情。令人惊讶的是,我也遇到了同样的问题。为了调试它,我研究了MediaPlayer apis并在我的代码中添加了MediaFailed事件处理程序。

令我惊讶的是,每次我播放一些东西时,处理程序都会被调用,内部异常如下:MILAVERR_INVALIDWMPVERSION (Exception from HRESULT: 0x88980507).

更多的谷歌搜索导致了this post,该网站表示,由于少数国家的反竞争政府政策,Windows10缺少常见的媒体应用程序。

要解决这个问题,您可以确保安装了WMP10或更高版本,也可以简单地使用SoundPlayer

private SoundPlayer player = new SoundPlayer();
player.SoundLocation = System.IO.Path.Combine(path, fileName);
player.Play();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52244497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档