我是编程新手,我创建了一个简单的mp3播放器。有一个文本框 txtCount ,当在该文本框中输入4需要播放mp3 4次..
这里我的代码总是播放一次,for循环也不起作用。
如果我在文本框中输入4当mp3文件一次播放时显示为 3次playd 而 1次需要播放这也是错误的我不能找到代码的错误。请帮我解决问题
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace mp3Player
{
class MusicPlayer
{
[DllImport("Winmm.dll")]
private static extern long mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength, int hwndCallback);
public void open(string file)
{
string command = "open \"" + file + "\" type MPEGVideo alias MyMp3";
mciSendString(command, null, 0, 0);
}
public void play()
{
string command = "play MyMp3";
mciSendString(command, null, 0, 0);
}
public void stop()
{
string command = "stop MyMp3";
mciSendString(command, null, 0, 0);
command = "close MyMp3";
mciSendString(command, null, 0, 0);
}
}
}
请参阅错误评论
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace mp3Player
{
public partial class Form1 : Form
{
int count, times = 0;
MusicPlayer player = new MusicPlayer();
public Form1()
{
InitializeComponent();
}
private void txtOpen_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
txtCount.Enabled = true;
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
label1.Text = openFileDialog1.SafeFileName;
player.open(openFileDialog1.FileName);
}
private void txtPlay_Click(object sender, EventArgs e)
{
if (txtCount.Text != "")
{
count = Int32.Parse(txtCount.Text);
txtCount.Enabled = false;
// This is does not work
for (times = 0; times < count; times++)
{
player.play();
times++;
lblCompleted.Text = times + " times Played";
lblPending.Text = (count - times) + " times need to play";
}
}
else {
txtCount.Focus();
}
}
private void txtStop_Click(object sender, EventArgs e)
{
player.stop();
}
}
}
答案 0 :(得分:0)
从循环内删除times++
。
for (times = 0; times < count; times++)
{
player.play();
//times++; //remove this line
//At the end of loop
//lblCompleted.Text = 3
//lblPending.Text = 1
lblCompleted.Text = times + " times Played";
lblPending.Text = (count - times) + " times need to play";
}
lblCompleted.Text
和lblPending.Text
会显示最新的更新值。
修改强> 您可以使用background worker播放音乐,在此期间GUI将等待更新,直到音乐结束。
答案 1 :(得分:0)
for循环从0开始,但是播放后但在更新标签之前,times变量增加1。 (你不需要在for循环中增加变量times ++(除了你想要它)
我认为您应该将代码更改为:
for (times = 1; times <= count; times++)
{
player.play();
lblCompleted.Text = times + " times Played";
lblPending.Text = (count - times) + " times need to play";
}