我刚刚开始制作节拍器应用程序但是我在计时器滴答声中播放样本声音时遇到了麻烦。我设置了计时器刻度,例如调用每1秒发出声音的方法。然后它出现了一个问题,即声音只播放一次,而不是更多。
所以,我的问题 - 如何在每个计时器滴答声中播放声音?
<Window x:Class="Metronome.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<TextBox Name="textBox1" />
<Button Name="button1" Content="Start" Click="button1_Click" />
<MediaElement Name="mediaElement1" Source="MetroBar1.wav" LoadedBehavior="Manual" />
</StackPanel>
</Grid>
using System.Collections.Generic;
using System.Linq;
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;
using System.Windows.Threading;
namespace Metronome
{
public partial class MainWindow : Window
{
const int secInMin = 60;
int beatRate;
double beatPerMsec;
DispatcherTimer timer1;
public MainWindow()
{
InitializeComponent();
timer1 = new DispatcherTimer();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
//beatRate = Convert.ToInt16(textBox1.Text);
//beatPerMsec = Math.Pow((beatRate / secInMin), -1) * 1000; //Amount of beats (timer ticks) per msec
// timer1.Tick += new EventHandler(metronome_Run);
timer1.Tick += metronome_Run;
//timer1.Interval = new TimeSpan(0, 0, 0, 0, Convert.ToInt16(beatPerMsec));
timer1.Interval = new TimeSpan(0, 0, 1);
timer1.Start();
}
private void metronome_Run(object sender, EventArgs e)
{
mediaElement1.Play();
}
}
}
答案 0 :(得分:4)
来自MSDN:
完成播放后,从当前位置播放媒体。
result.content.length
> 12047
不会自动重置其位置。在调用MediaElement
之前,您需要手动将Position
重置为开头。
Play
在调用private void metronome_Run(object sender, EventArgs e)
{
mediaElement1.Position = new TimeSpan(0);
mediaElement1.Play();
}
之前调用Stop
可能更安全,具体取决于声音文件的长度。 Play
将自动重置为开头,并中断当前播放的任何声音。
Stop