MediaElement卷 - 速度

时间:2018-04-26 13:53:30

标签: c# vb.net uwp

我正在构建一个MediaElement的UWP应用 我希望能够更改MediaElement的音量和播放速度,但我的代码无法正常工作。
如果我在第一次播放之前设置音量和速度,但是如果我改变例如。播放后的音量不会改变音量。

我的代码:

Private mElement As MediaElement

Private Async Sub MainPage_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    mElement = New MediaElement
    AddHandler mElement.MediaEnded, AddressOf OnMediaEnded
End Sub

Async Function SayAsync(ByVal text As String) As Task
    If Synth Is Nothing Then
        Dim chosenVoice = SpeechSynthesizer.AllVoices.First(Function(v) v.DisplayName.Contains(cboVoice.SelectedItem.ToString))
        Synth = New SpeechSynthesizer() With {.Voice = chosenVoice}
    End If
    currentStream = Await Synth.SynthesizeTextToStreamAsync(text)
    mElement.Volume = SpeechVol / 100
    mElement.PlaybackRate = SpeechSpeed / 100
    mElement.SetSource(currentStream, String.Empty)
    mElement.Play()
End Function

Private Sub OnMediaEnded(ByVal sender As Object, ByVal e As RoutedEventArgs)
    currentStream?.Dispose()
    currentStream = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

通过测试,我可以在播放音频时正确更改Volume。由于您的代码段只是整体的一部分,以下是一个完整的演示,可以很好地在我身边:

XAML

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" x:Name="rootgrid"> 
   <Button x:Name="btnstart" Click="btnstart_Click" Content="start play"></Button>
   <Button x:Name="btnchangevolume" Click="btnchangevolume_Click" Content="change volume to 50" Margin="100"></Button>
</Grid>

背后的代码

Inherits Page

Private mElement As MediaElement
Private Synth As SpeechSynthesizer
Private currentStream As SpeechSynthesisStream 

Private Async Sub MainPage_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    mElement = New MediaElement
    rootgrid.Children.Add(mElement)
End Sub

Async Function SayAsync(ByVal text As String) As Task
    Synth = New SpeechSynthesizer
    currentStream = Await Synth.SynthesizeTextToStreamAsync(text)
    mElement.Volume = 10 / 100
    mElement.PlaybackRate = 50 / 100
    mElement.SetSource(currentStream, String.Empty)

End Function

Private Async Sub btnstart_Click(sender As Object, e As RoutedEventArgs)
    Await SayAsync("The privacy statement was declined." +
       "Go to Settings -> Privacy -> Speech, inking and typing, and ensure you" +
       "have viewed the privacy policy, and 'Get To Know You' is enabled.")
End Sub

Private Sub btnchangevolume_Click(sender As Object, e As RoutedEventArgs)
    mElement.Volume = 50 / 100
End Sub

可能的原因可能是,在创建代码后,您没有将MediaElement添加到XAML。如果您仍有问题,请提供最小的转载项目。

顺便说一句,在Windows 10中,构建1607或更高版本,我们建议您使用MediaPlayerElement代替MediaElement