我正在用C#在WinForm中创建一个简单的音乐(mp3)播放器。
我想要实现的是:
1)播放选定的音乐文件
2)音乐播放时自动移动TrackBar
3)允许用户前后移动轨迹栏,以便他们可以从轨迹中的任何位置播放音乐。 (虽然音乐也在播放)
我让#1和#2正常工作。但是,我很难实现#3。当我覆盖此值时,音乐演奏起来很不稳定。这是我的代码。
private AxWMPLib.AxWindowsMediaPlayer player;
/*Play the music file selected (#1) */
private void BtnPlay_Click(object sender, EventArgs e)
{
player = new AxWMPLib.AxWindowsMediaPlayer();
player.CreateControl();
player.URL = filePath; //Initialized somewhere in the code
player.PlayStateChange += player_PlayStateChange;
player.Ctlcontrols.play();
}
private void player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (player.playState == WMPLib.WMPPlayState.wmppsPlaying)
{
MyTrackBar.Maximum = (int)player.Ctlcontrols.currentItem.duration;
TmrPlay.Start();
}
else if(player.playState == WMPLib.WMPPlayState.wmppsStopped)
{
TmrPlay.Stop();
MyTrackBar.Value = 0;
}
}
/*Move the TrackBar automatically with Timer. (#2) Runs every 100 ms */
private void TmrPlay_Tick(object sender, EventArgs e)
{
if (player.playState == WMPLib.WMPPlayState.wmppsPlaying)
MyTrackBar.Value = (int)player.Ctlcontrols.currentPosition;
}
/* Trying to play music from anywhere when the TrackBar is manually moved.
For example, they can move the TrackBar and move it towards the end of the
music, WHILE THE MUSIC IS PLAYING. */
/* With this below event code, I can move the TrackBar freely, but the music
plays very choppy because it keeps changing the currentPosition. */
private void MyTrackBar_ValueChanged(object sender, EventArgs e)
{
player.Ctlcontrols.currentPosition = MyTrackBar.Value;
}
在移动TrackBar时,谁能给我一些如何播放音乐的建议?
答案 0 :(得分:2)
您面临的问题是,您正在从tick事件中更新轨迹栏,然后触发播放器位置重新更新到它所在的位置。因此,每个刻度都会强制轨迹栏更新两次,这会导致您遇到的结巴。
要解决此问题,如果出现滴答声事件,则无需更新玩家位置。
一个类级的bool变量可以解决问题:
private bool ticking = false;
在您的TmrPlay_Tick
中,应将ticking
设置为true:
if (player.playState == WMPLib.WMPPlayState.wmppsPlaying)
{
ticking = true;
MyTrackBar.Value = (int)player.Ctlcontrols.currentPosition;
}
如果勾选为true,则在MyTrackBar_ValueChanged事件中不要再次更新轨迹栏:
if (ticking)
{
ticking = false;
}
else
{
player.Ctlcontrols.currentposition = MyTrackBar.Value;
}