I set an int called playercount as 1 at the start and did the following..
private void button2_Click(object sender, EventArgs e)
{
playercount++;
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = "Super Mario Bros.mp3";
if (playercount % 2 == 0)
{
button2.Text = "Music Toggle: ON";
wplayer.controls.play();
}
else
{
wplayer.controls.stop();
button2.Text = "Music Toggle: OFF";
}
}
For some reason the music stop doesn't seem to work. Is there something im doing wrongly ?
You are creating a new instance of WindowsMediaPlayer each time the button is clicked. This means that your stop() call will not affect the player you create on the first click which you play().
You need to create the player as a class-level variable and act on that.
You playercount logic is a bit dubious too as InvernoMuto pointed out. Is a simple bool not sufficient?
private bool musicPlaying = false;
private WMPLib.WindowsMediaPlayer wplayer = null;
private void button2_Click(object sender, EventArgs e)
{
// create player only if necessary
if(wplayer == null)
{
wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = "Super Mario Bros.mp3";
}
// toggle musicPlaying
musicPlaying = !musicPlaying;
if (musicPlaying)
{
button2.Text = "Music Toggle: ON";
wplayer.controls.play();
}
else
{
wplayer.controls.stop();
button2.Text = "Music Toggle: OFF";
}
}
Related
I have a project I'm working on. music playing platform. i use windows media player for this but i have a problem. The music comes as a list from the database. There is a play button at the top of the lists. When I press the button, the music plays smoothly. but when I play another song, the other music doesn't stop and they both play at the same time. I need your help. I think the problem is caused by the following codes
private bool durum = false;
public void btn_koynat_Click(object sender, EventArgs e)
{
Form1 frm1 = (Form1)this.FindForm();
frm1.player = player;
if (durum == true)
{
durum = false;
frm1.sarkislider.Value = 0;
}
if (durum==false)
{
durum = true;
int sec = Convert.ToInt32(label_sec.Text);
frm1.btn_Oynat.Enabled = true;
frm1.durum = true;
player.URL = label_sarki.Text + ".MP3";
btn_koynat.BackgroundImage = Properties.Resources.sesacik;
frm1.btn_Oynat.BackgroundImage = Properties.Resources.durdurbutonu;
frm1.sarki_isim.Text = label_sarki.Text;
frm1.sarki_sanatci.Text = label_sanatci.Text;
frm1.label_timer2.Text = label3.Text;
frm1.sarkislider.Maximum = sec;
frm1.timer1.Enabled = true;
frm1.sarkislider.Value = 0;
player.controls.play();
}
}
You can use wplayer.playState to check if your player is running.
Here is a code example, which can avoid playing two songs at the same time.
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
private void button1_Click(object sender, EventArgs e)
{
if (wplayer.playState == WMPLib.WMPPlayState.wmppsPlaying)
{
wplayer.controls.stop();
wplayer.URL = comboBox1.SelectedItem.ToString();
wplayer.controls.play();
}
else
{
wplayer.URL = comboBox1.SelectedItem.ToString();
wplayer.controls.play();
}
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("1.mp3");
comboBox1.Items.Add("2.mp3");
comboBox1.Items.Add("3.mp3");
comboBox1.Items.Add("4.mp3");
comboBox1.Items.Add("5.mp3");
}
Note: I used combobox to store mp3 files. Based on my test, when I play a mp3 file and click button to play another mp3 file, the initial mp3 file was stopped and play another file.
Long Story Short,
The app I am making will Launch a Game.
The Start button will then Check to make sure the games EXE is running..
IF it is running, it will run a script to press buttons 1, 2, and 3..
After that it will loop that script, but first checking if the game has not crashed (if it crashed it wont run the loop)
My Issue:
While the loop is running, which is using System.Threading.Thread.Sleep,
does not let other functions of the app preform (in this case showing and hiding button, and changing label colors.) The main reason this is important is the button it wont is the Stop button which is suppose to end the looping script.
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
Timer timer;
Stopwatch sw;
public Form1()
{
InitializeComponent();
button4.Visible = false;
button2.Enabled = false;
}
private void timer_Tick(object sender, EventArgs e)
{
label2.Text = sw.Elapsed.Seconds.ToString() + "seconds";
Application.DoEvents();
}
// ===============================================
// BUTTON FUNCTIONS
// ===============================================
// Launch GAME
private void button1_Click(object sender, EventArgs e)
{
// Launch GAME
Process.Start(#"C:\Windows\System32\Notepad.exe");
button2.Enabled = true;
}
// START BOT
private void button2_Click(object sender, EventArgs e)
{
status.Text = #"Starting Bot..";
timer = new Timer();
timer.Interval = (1000);
timer.Tick += new EventHandler(timer_Tick);
sw = new Stopwatch();
timer.Start();
sw.Start();
BotReady(sender, e);
}
// PLAYER DIED
private void button3_Click(object sender, EventArgs e)
{
KillBot(sender, e);
status.Text = #"lol u ded";
}
// STOP THE BOT
private void button4_Click(object sender, EventArgs e)
{
KillBot(sender, e);
status.Text = #"Bot Stopped";
button2.Visible = true;
button4.Visible = false;
button2.Enabled = true;
}
// KILL GAME AND BOT (IF IT CRASHED OR SOMETHING)
private void button5_Click(object sender, EventArgs e)
{
}
// ===============================================
// OTHER FUNCTIONS
// ===============================================
// Target GAME application
private void TargetAQ(object sender, EventArgs e)
{
// this part doesnt work yet.
// Selection.Application and Tab to it
}
// CHECK IF GAME IS STILL RUNNING, KILL BOT IF GAME IS NOT DETECTED
public void CheckStatus(object sender, EventArgs e)
{
Process[] GAME = Process.GetProcessesByName("notepad");
if (GAME.Length == 0)
// GAME NOT running
{
KillBot(sender, e);
button2.Enabled = false;
status.Text = #"GAME is not Running, Bot Stopped.";
uGAME.ForeColor = Color.Red;
button2.Visible = true;
button4.Visible = false;
button2.Enabled = false;
}
else
// GAME IS running
{
status.Text = #"GAME is Running!";
uGAME.ForeColor = Color.Green;
button2.Visible = false;
button4.Visible = true;
}
}
// Verify bot and GAME are running before starting
public void BotReady(object sender, EventArgs e)
{
CheckStatus(sender, e);
if (uGAME.ForeColor == Color.Green)
{
status.Text = #"Bot Started!";
Botting(sender, e);
}
else { status.Text = #"GAME is not running"; }
}
//THE BOT ACTIONS
public void Botting(object sender, EventArgs e)
{
// Check to make sure everything is still running
CheckStatus(sender, e);
TargetAQ(sender, e);
if (uGAME.ForeColor == Color.Green)
{
// all is running, then you good.
Script(sender, e);
}
//GAME died, kill scripts
else {
KillBot(sender, e);
status.Text = #"GAME Crashed:(";
}
}
//Things it does in-game
public void Script(object sender, EventArgs e)
{
status.Text = #"Bot in progress..";
// Use skills in game rotation
System.Threading.Thread.Sleep(3000);
SendKeys.Send("1");
System.Threading.Thread.Sleep(3000);
SendKeys.Send("2");
System.Threading.Thread.Sleep(3000);
SendKeys.Send("3");
// Go back and check the game has not crashed before re-running the script
Botting(sender, e);
}
// STOP THE BOT AND TIME COUNTER
public void KillBot(object sender, EventArgs e)
{
// kill the clock and bot
status.Text = #"Stopping bot...";
timer.Stop();
sw.Stop();
label2.Text = sw.Elapsed.Seconds.ToString() + " seconds";
status.Text = #"Bot Stopped";
}
}
}
I have a similar question as last time, but no matter how much I hit my head against the wall, solution is not coming. The problem is that the message box gets created too many times, when it should only open once, unsubscribe from documentCompleted and then exit. Thanks again!
private void textBox4_TextChanged(object sender, EventArgs e)
{
if (textBox4.Text.Length >= 3)
{
timer1.Enabled = true;
}
}
private void timer1_Tick_1(object sender, EventArgs e)
{
if (textBox4.Text != "")
{
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate("https://worldofwarcraft.com/en-gb/search?q=" + textBox4.Text);
webBrowser1.DocumentCompleted += GetImg; //sub here
}
}
private void GetImg(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string img_url = "";
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
{
if (el.GetAttribute("className") == "Avatar-image")
{
img_url = (el.OuterHtml).Substring(el.OuterHtml.IndexOf("https"));
img_url = img_url.Substring(0, img_url.IndexOf(")"));
pictureBox1.ImageLocation = img_url;
}
else if (el.GetAttribute("className") == "Character-level")
{
textBox5.Visible = true;
label7.Visible = true;
string lvl_url = "";
lvl_url = (el.InnerHtml).Substring(3);
lvl_url = lvl_url.Substring(0, lvl_url.IndexOf("<"));
textBox5.Text = lvl_url;
DialogResult YESNO = MessageBox.Show("Is this your character?", "Select your char", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (YESNO == DialogResult.Yes)
{
// clean up
webBrowser1.DocumentCompleted -= GetImg; //unsub here
pictureBox1.Enabled = false;
timer1.Dispose();
break;
}
}
}
}
You need to either set timer1.Enabled to false or call timer1.Stop() as soon as you enter the timer1_Tick_1 method, or the timer will keep firing and calling your method every time.
My goal is to use my webcam to capture my face and detect my mood by facial expression. The output should be probabilites like 70 % happy, 10 % sad, ...
My approach: very happy and very sad ( and other states ) faces should be saved in a HaarCascade.
My problems are twofold:
How do I create a HaarCascade to use with HaarObjectDetector for the
HaarObjectDetector object to output percentages instead of
outputting a "true" when a threshold is being surpassed?
How do I create a HaarCascade for HaarCascade? Is it easier to use String path = #"C:\Users\haarcascade-frontalface_alt2.xml"; HaarCascade cascade1 = HaarCascade.FromXml(path); with opencv-xml or generate it using HaarCascade m = new HaarCascade(20,20,HaarCascadeStages);? What would HaarCascadeStages be?
Have others already solved this issue and offer sourcecode for c#?
My current code:
public partial class Form1 : Form
{
private bool DeviceExist = false;
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource = null;
Bitmap picture;
HaarObjectDetector detector;
FaceHaarCascade cascade;
public Form1()
{
InitializeComponent();
}
// get the devices name
private void getCamList()
{
try
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
comboBox1.Items.Clear();
if (videoDevices.Count == 0)
throw new ApplicationException();
DeviceExist = true;
foreach (FilterInfo device in videoDevices)
{
comboBox1.Items.Add(device.Name);
}
comboBox1.SelectedIndex = 0; //make dafault to first cam
}
catch (ApplicationException)
{
DeviceExist = false;
comboBox1.Items.Add("No capture device on your system");
}
}
//toggle start and stop button
private void start_Click(object sender, EventArgs e)
{
}
//eventhandler if new frame is ready
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
picture = (Bitmap)eventArgs.Frame.Clone();
//Rectangle[] objects = detector.ProcessFrame(picture);
//if (objects.Length > 0)
//{
// RectanglesMarker marker = new RectanglesMarker(objects, Color.Fuchsia);
// pictureBox1.Image = marker.Apply(picture);
//}
pictureBox1.Image = picture;
}
//close the device safely
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
//get total received frame at 1 second tick
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = "Device running... " + videoSource.FramesReceived.ToString() + " FPS";
}
//prevent sudden close while device is running
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CloseVideoSource();
}
private void Form1_Load(object sender, EventArgs e)
{
getCamList();
cascade = new FaceHaarCascade();
detector = new HaarObjectDetector(cascade, 30);
detector.SearchMode = ObjectDetectorSearchMode.Average;
detector.ScalingFactor = 1.5f;
detector.ScalingMode = ObjectDetectorScalingMode.GreaterToSmaller;
detector.UseParallelProcessing = false;
detector.Suppression = 2;
}
private void rfsh_Click_1(object sender, EventArgs e)
{
}
private void start_Click_1(object sender, EventArgs e)
{
if (start.Text == "Start")
{
if (DeviceExist)
{
videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
CloseVideoSource();
videoSource.DesiredFrameSize = new Size(640, 480);
//videoSource.DesiredFrameRate = 10;
videoSource.Start();
label2.Text = "Device running...";
start.Text = "Stop";
timer1.Enabled = true;
}
else
{
label2.Text = "Error: No Device selected.";
}
}
else
{
if (videoSource.IsRunning)
{
timer1.Enabled = false;
CloseVideoSource();
label2.Text = "Device stopped.";
start.Text = "Start";
}
}
}
}
I intend to put a timer in my the following code so that that the button will be enabled again after 5 seconds. AS you can see, my send button will be disabled after the user send 5 message. I want to enabled it after 5 seconds have elapsed.
Any suggestion is welcomed.
public bool stopSpam(int counter)
{
int spam = counter;
if (spam < 6)
{
return false;
}
else
{
return true;
}
}
private void button1_Click(object sender, EventArgs e)
{
counter++;
bool check = stopSpam(counter);
if (check == false)
{
if (textBox2.Text != "")
{
if (textBox2.Text.ToLower().StartsWith("/"))
{
onCommand(textBox2.Text);
string datetimestring = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}.txt", DateTime.Now);
String exePath = string.Format(Application.StartupPath + "\\logs\\" + "msglogs {0}", datetimestring);
StreamWriter writer = File.CreateText(exePath);
writer.Write(textBox1.Text);
writer.Close();
textBox2.Text = "";
}
else
{
m_ChildConnection.SendMessage("MSG :" + textBox2.Text);
string datetimestring = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}.txt", DateTime.Now);
String exePath = string.Format(Application.StartupPath + "\\logs\\" + "msglogs {0}", datetimestring);
StreamWriter writer = File.CreateText(exePath);
writer.Write(textBox1.Text);
writer.Close();
textBox2.Text = "";
}
}
}
else
{
button1.Enabled = false;
}
Thanks in adavence!
Have a timer, set its interval to 5 seconds (5000). Keep it disabled by default.
When the button is pressed enable the timer
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
timer.Enabled = true;
}
When a tick occurs after 5 seconds, enable the button and disable the timer again.
private void timer_Tick(object sender, EventArgs e)
{
button1.Enabled = true;
timer.Enabled = false;
}
Hard to figure out what you're trying to achieve but you could take the following steps to disable the enable the button after 5 seconds.
Add:
private Timer t;
as a class variable.
then after your InitializeComponent add:
t = new Timer(5000){Enabled = false, Tick += (myTick)};
then add this method:
private void myTick(object source, ElapsedEventArgs e)
{
button1.Enabled = true;
}
Also, consider updating this method:
your stopSpam method to:
public bool stopSpam(int counter)
{
return counter >= 6;
}
In fact, there is actually no need for the method:
Simply change
if(check == false)
to
if(counter > 5)
You can simply use System.Timers.Timer class to put timer.
//Define the timer
private System.Timers.Timer buttonTimer;
// Initialize the timer with a five second interval.
buttonTimer= new System.Timers.Timer(5000);
// Hook up the Elapsed event for the timer.
buttonTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
//Start the timer
buttonTimer.Start();
// Enable the button in timer elapsed event handler
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
button1.Enabled = true;
}