How can I play a sound in a thread? - c#

I want to play a beep for 1 second in thread. I'm not familiar with threads and maybe there is another easy way without using threads. I used console.beep(), but unfortunately it freeze's the form for a second.
while(true)
{
do some jobs;
console.beep();
}
The Winform app freeze on the console.beep(); for one second. I need to pass the line and simultaneously beep for one second.

You can use
using System.Media;
SystemSounds.Beep.Play();
And Play() doesn't block so you don't need a Thread.
It plays whatever is configured in the User's sytem sound settings.
But if you need to know when the sound has finished this is not what you want.
How to: Play a Beep from a Windows Form

Related

iOS background thread slow down when UI is idle

A bit of context first
I have a Xamarin app that essentially streams video from a remote server. I have a background thread that loops like this (pseudo-code):
private void UpdateMethod()
{
while (running)
{
bool success = WaitForUpdate();
if (!success)
{
break;
}
Update update = GetUpdate();
SendUpdateToConcurentQueue(update);
}
Disconnect();
}
I start the background thread like this:
Thread thread = new Thread(UpdateMethod);
thread.IsBackground = true;
thread.Start();
The issue
When I start the stream, everything is perfect. It's only after ~10 seconds of not interacting with the device that it becomes really slow. I've outputted the number of updates from the background thread, and they seem to come in a lot slower. I usually get around 2-6 updates to process per update (60fps). When it's super slow, I get 1 ever 6 update cycle.
One thing that puzzles me: When I pull down the iOS top bar menu, the updates go back up and the stream is suddenly back to normal speed. Update rate goes up for ~10 seconds and it goes back to lagging like crazy.
What I've tried
I tried to start a Dispatch queue with only this in it, like this:
DispatchQueue queue = new DispatchQueue("updateQueue");
queue.DispatchAsync(this.UpdateProcess);
It didn't seem to help at all.
I also tried to change the QualityOfService property in my update thread like this:
NSThread.Current.QualityOfService = NSQualityOfService.UserInitiated
Doesn't work either! It seems to me that iOS lowers my thread's priority for some reason. If I put a breakpoint in my UpdateMethod method, it's being hit when the app doesn't lag. But when there's lag, the breakpoint doesn't get hit. Now this really puzzles me, since the code still runs! I still receive the updates, it's just way slower...
Edit: I tested using Instruments and found that the network is being throttled... Investigating, but if anyone has knowledge of any kind of network throttle on iOS, let me know.
Try setting the IdleTimerDisabled to true, we do this all the time in iOS games to keep iOS from idling our games.
Note: We do this in a polite way only when the user is not touching the screen due to watching a replay, level changing multimedia segues, etc...
Note: Make sure that you do reset the idle when you do not need it (when you app does go in the background, etc...), as from killing battery and making users bummed out about your app to the real killer: Apple Store rejections
Apple: App Idle Timer info
Xamarin: UIKit.UIApplication.IdleTimerDisabled Property
The default value of this property is NO. When most apps have no touches as user input for a short period, the system puts the device into a "sleep” state where the screen dims. This is done for the purposes of conserving power. However, apps that don't have user input except for the accelerometer—games, for instance—can, by setting this property to YES, disable the “idle timer” to avert system sleep.
| IMPORTANT
You should set this property only if necessary and should be sure to reset it to NO when the need no longer exists. Most apps should let the system turn off the screen when the idle timer elapses. This includes audio apps. With appropriate use of Audio Session Services, playback and recording proceed uninterrupted when the screen turns off. The only apps that should disable the idle timer are mapping apps, games, or programs where the app needs to continue displaying content when user interaction is minimal.

How to write AVI from a Callback, keep UI responsive and wait for completion

I have to use a camera SDK for a microscope that comes with a sample C# Windows Forms application.
The SDK functions are imported to the app via DLLImport.
In this sample application the single frames from the camera are read from RAM via a callback function.
This callback function then updates a PictureBox to show the live image.
For my useage however I want to not only show the frames, but also record them.
I think the easiest way to do this is by using SharpAvi.
However I don't know how to initialize the AviWriter (I obviously can't initialize it everytime the callback fires) and then add the single frames to the stream from the callback function.
At the moment I solved my problem by using another function that waits in a seperate thread for a public counter to go up - the counter itself is updated in the callback function.
Everytime the counter is updated this function then also reads the frame from RAM and adds it to the AviWriterStream.
To top it of I had to make the thread block my UI by using
var resetEvent = new ManualResetEvent(false);
System.Threading.ThreadPool.QueueUserWorkItem(delegate
{
WriteAVI()
resetEvent.Set();
}, null);
resetEvent.WaitOne();
This is due to the fact that I need to record several videos at different XY positions - so everytime my for loop arrives at a new XY position the recording is triggered and I have to make sure to only move to the next position once the recording is actually finished.
My way of doing this is obviously hackish and very bad practice (I already feel bad but just don't know better) and I am wondering what the correct solution would be.
So far it works - just the UI freeze is really annoying.
Edit: These are probably two questions:
1) How to correctly write frames to the AVI and
2) How to wait for the recording to be completed without making it freeze my UI

Why windows media player is not closing with player.Close() method?

I am creating a media player object in a simple console application, to play some file. Though the media player is getting launched successfully, when I am using the close() method, the process still runs and media player window does not close. what needs to be done? here is the code I wrote..
WindowsMediaPlayer player= new WindowsMediaPlayer();
player.OpenPlayer("c:\\abc.wmv");
Thread.Sleep(2000);
player.controls.stop();
player.close();
Here the process doesn't exit and file still keeps running. How can I close the application?
The automation interface doesn't have a way to force the player to exit. The less than ideal approach is to kill it:
var prc = Process.GetProcessesByName("wmplayer");
if (prc.Length > 0) prc[prc.Length - 1].Kill();
The better mouse trap is to embed the player into your own GUI, easy to do with Winforms.
I think you need to close the COM object by calling Marshal.ReleaseComObject. COM does not know that you will never be using the player again, so it cannot close the process.
Do not rely on garbage collection for this because it might never happen if there is no memory pressure. Call Marshal.ReleaseComObject manually.

Play sound till dialogbox.dialogresult == dialogresult.OK

I am developing a winform application.
I want to play a sound file, till the dialogresult is OK for a message box. How can i achieve that.
For e.g.
/*Till*/ (MessageBox.Show("Alarm") == DialogResult.OK)
//Play a sound file
I tried while and do while but didn't succeed. Do i need to use background worker or run the code in a separate thread ??
You don't need to roll your own threading. .NET class library already did it for you. This is how you can do it:
SoundPlayer p = new SoundPlayer(#"C:\Windows\Media\chimes.wav");
p.PlayLooping();
MessageBox.Show("Alarm");
p.Stop();
Yes, run the sound file in a seperate thread which you start when the messagebox pops up. Once the MessageBox comes back with OK you can make a call into that thread telling the music to stop, or you could kill the thread.
EDIT
An alternative would be to write your own AlarmMessageBox which inherits from MessageBox. Its only difference would be that upon creation it would start playing that sound and upon clicking ok it would stop. This could work in just one thread.

How to pause execution yet keep webbrowser control loading in C#

I'm trying to make a web browser that tells me when a specific video is done. I already know how to get the time in seconds of how long it takes. I just need to know how to wait to execute the next step without stopping the webbrowser control (which needs to play the flash video).
Any ideas? I've been looking into the Timer class, but can't figure out how to apply it to this problem.
Thanks.
Well, you could try Thread.Sleep() (You're not clear about what threads are running what...), except this idea is doomed to failure. I mean, you are going to let him pause the video, aren't you?
(Yes, You are!)

Categories