I have linked the import button with a media element so i can get the song to play.
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".txt";
dlg.Filter = "WAV Files (*.wav)|*.wav|MP3 Files (*.mp3)|*.mp3|MP4 Files (*.mp4)|*.mp4|WMA Files (*.wma)|*.wma|SWA (*.swa)|*.swa";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
meMedia1.Source = new Uri(dlg.FileName);
meMedia1.Play();
//txtFileLocation.Text = filename;
Now, the sound plays but what I want to do is link a slider so they can skip some of the song and also a label above the slider so that it read how long into the song it is. This is how my application looks now to give you an idea.
http://i.stack.imgur.com/sVtrd.png
Thank You.
EDIT : Got the seek to change the song position but I still cant get it manually moving to the time of the song, for example if I skip to the middle of the song, and let the song finish my slider will still be in the middle and I want it to be at the end.
One approach is to create a DispatcherTimer that ticks every 200-800ms (depending on your preference for update speed) that syncs the slider to the player's current Position. That code might look similar to this:
// In the class members area
private DispatcherTimer _timer = null;
// In your constructor/loaded method
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(500);
_timer.Tick += _timer_tick;
// Timer's tick method
void _timer_tick(object sender, EventArgs e)
{
// Convert duration to an integer percentage based on current position of
// playback and update the slider control
TimeSpan ts = meMedia1.NaturalDuration.TimeSpan;
int percent = int( meMedia1.Position / ts.Seconds * 100 );
mySliderControl.Value = percent;
}
Note that this assumes you have a Slider whose Min is 0 and Max is 100. You can bump it up to 0-1000 (and change the math accordingly) to get finer granularity. This also doesn't allow the slider to push user interaction back to the player, but gives you an idea of one way to get the opposite. You can add an event handler to the Slider such that when the user begins interacting, this _timer is stopped ( _timer.Stop() ) so updates to the media position stop updating the slider and instead start doing your slider -> media position updates instead. Then when the user lets go of the slider, turn the _timer back on ( _timer.Start() ).
Related
I am new to C#. Basically I want to implement an auto save function using a timer. May I know how do I have to implement it, so that the text will get saved automatically every 5 seconds?
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.DefaultExt = "*.rtf";
saveFile1.Filter = "RTF Files|*.rtf";
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
txtb.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);
I can save the file but how do I auto save it?
Just use a timer with an interval of 5000ms
Timer tmr = New Timer;
tmr.Interval = 5000;
Now call your timer in the Form_Load event or whereever you want to call it the first time. After that, just use the Tick event of the timer (Note: The first time you call the SAVEFILEDIALOG, make sure that you store the location in some variable so that you can keep on reusing it to save the text file which will eliminate the need of using the SAVEFILEDIALOG again and again):
String pathOfFile;
private sub FirstTimeSaveIt_Click // the button that saves it first
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
pathOfFile = saveFile1.FileName
txtb.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);
}
private void tmr_Tick()
{
tmr.Stop();
txtb.SaveFile(pathOfFile, RichTextBoxStreamType.PlainText);
tmr.start();
}
I have a XAML based Windows 10 UWP application which uses a MediaElement to play videos. For analytics purpose, when a user plays a video, I want to track the start and end positions of a seek operation.
The only event I can find is SeekCompleted, in which I can get the end position using mediaElement.Position but I can't see any way to identify the start position. Also CurrentStateChanged event is not fired when the seek operation starts. How do I get the start position?
Code that I am using:
mediaElement.CurrentStateChanged += MediaElement_StateChanged;
mediaElement.SeekCompleted += MediaElement_SeekCompleted;
//Play the video
var mediaSource = MediaSource.CreateFromUri(new Uri(streamUrl));
var mediaPlaybackItem = new MediaPlaybackItem(mediaSource);
mediaElement.SetPlaybackSource(mediaSource);
public void MediaElement_StateChanged(object sender, RoutedEventArgs e)
{
var mediaElement = sender as MediaElement;
var state = mediaElement.CurrentState;
var position = mediaElement.Position;
}
public void MediaElement_SeekCompleted(object sender, RoutedEventArgs e)
{
var position = mediaElement.Position;
}
Both methods get called only after the seek operation is completed and so I can get only the end position. I need the start position as well.
The default transport controls do not raise any event when you start seeking. To get this you could modify them so that such an event is raised.
There's documentation on customizing the transport controls at https://learn.microsoft.com/en-us/windows/uwp/controls-and-patterns/custom-transport-controls
These show how to get programmatic access to the Slider used for seeking. You could add a handler for a suitable event (perhaps DragStarting, Holding, or ManipulationStarted?) and then record the current position then.
I am trying to create a WPF media application for running audio files using Media Element.
I succeeded in it . But i want to schedule playing a songs which i selected in some interval of time repeatedly. Say 10'o clock in every day or in every hour etc..
What is the best way to do that ?
Initially am think about doing it using a Timer. But that makes my code complex because i have to play multiple songs in different intervals set by user.
Recently i go to know about Task Scheduler and i run their sample code [open a notepad] and it works perfectly.
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(#"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
How do i define an action which play a song on this context ? Currently they are providing ExecAction,SendEmail,ShowMessage and ComHandlerAction see this link
Or Can we invoke play method of my application by this Task Scheduler? Please help me by providing any idea .
Thanks
First, you would need to order your collection of times with the closest time first. Then, you would only need one DispatcherTimer and you could set its Interval value to the length of time between now and the first time from your collection:
private DispatcherTimer mediaPlayerTimer = null;
...
mediaPlayerTimer = new DispatcherTimer();
mediaPlayerTimer.Interval = YourFirstDateTime.Subtract(DateTime.Now);
mediaPlayerTimer.Tick += MediaPlayerTimer_Tick;
mediaPlayerTimer.Start();
...
private void MediaPlayerTimer_Tick(object sender, EventArgs e)
{
mediaPlayerTimer.Stop();
// Load next audio file and play
// Remove YourFirstDateTime from your collection
// Set YourFirstDateTime = the next item from the collection
mediaPlayerTimer.Interval = YourFirstDateTime.Subtract(DateTime.Now);
mediaPlayerTimer.Start();
}
I am writing a custom audio player in c# using the MediaPlayer class. I have implemented a scroll bar so the user can seek through a track and this is where I am having the problem.
WHen the user selects an audio track (loaded from an xml playlist) the app calculates the length in seconds of the track and sets this as the max value for the scroll bar. This all works fine except the NaturalDuration.TimeSpan property sometimes returns 0 rather than the amount. I have proved this by adding a loop that exits when NaturalDuration.HasTimeSpan is true then returns the NaturalDuration.TimeSpan value.
My question is how can I just get the NaturalDuration.TimeSpan when the NaturalDuration.HasTimeSpan is changed to true?
The correct way to do this is to handle the MediaPlayer.MediaOpened event:
mediaPlayer = new MediaPlayer();
mediaPlayer.MediaOpened += MediaPlayer_MediaOpened;
mediaPlayer.Open(new Uri(mediaFilePath, UriKind.Absolute));
...
private void MediaPlayer_MediaOpened(object sender, EventArgs e)
{
if (mediaPlayer.NaturalDuration.HasTimeSpan)
{
SliderMaximum = mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds;
mediaPlayer.Play();
}
}
I have a NotifyIcon in my program which displays a baloon tip in the taskbar. I wrote code as
notifyIcon1.Icon = new Icon(SystemIcons.Application, 40, 40);
notifyIcon1.Visible = true;
notifyIcon1.Text = "Test Notify Icon Demo";
notifyIcon1.BalloonTipText =count+ " Alerts";
notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
notifyIcon1.BalloonTipTitle = "Alert!";
notifyIcon1.ShowBalloonTip(999999999);
The baloon tip is invisible after the set time (999999999). But I want to show the baloon tip until it is clicked as I have baloontipclicked event.
How to make baloontip visible forever?
from MSDN:
Minimum and maximum timeout values are enforced by the operating
system and are typically 10 and 30 seconds, respectively, however this
can vary depending on the operating system. Timeout values that are
too large or too small are adjusted to the appropriate minimum or
maximum value. In addition, if the user does not appear to be using
the computer (no keyboard or mouse events are occurring) then the
system does not count this time towards the timeout.
it seems not be possible to override the maximum timeout (eventually adjusted by Windows and limited to 30 seconds even if you specify a longer one) so the Notification will fade away, will not wait for you to click on it after 2 minutes.
if you want to really have a different behavior you should probably use something else, other objects or simulate something similar with forms where you have the full control on the behavior and you can show, hide and close as you wish from your code.
You can show it again if it hasn't been clicked.
You have the close event (BalloonTipClosed), if user hasn't ckicked it just show it again.
private void ShowBalloonTip(int minutes) {
notifyIcon.BalloonTipIcon = ToolTipIcon.Error;
notifyIcon.BalloonTipText = "Text";
notifyIcon.BalloonTipTitle = "Title";
notifyIcon.ShowBalloonTip(minutes* 60 * 1000);
m_showUntil = DateTime.Now.AddMinutes(minutes);
}
private void notifyIcon_BalloonTipClosed(object sender, EventArgs e) {
if (m_showUntil > DateTime.Now)
notifyIcon.ShowBalloonTip(60 * 1000);
}
private void notifyIcon_BalloonTipClicked(object sender, EventArgs e) {
m_showUntil = DateTime.MinValue;
(..)
}