Как создать ползунок и индикатор выполнения для музыкального проигрывателя WPFC#

Место общения программистов C#
Ответить
Anonymous
 Как создать ползунок и индикатор выполнения для музыкального проигрывателя WPF

Сообщение Anonymous »

Как я могу создать ползунок, который может контролировать продолжительность воспроизведения песни и перемещаться в зависимости от продолжительности песни. У меня есть этот код xaml для ползунка и индикатора выполнения:




У меня есть отдельные кнопки «Воспроизвести», «Пауза», «Возобновить», «Остановить». Когда я воспроизвожу песню после выбора этой песни в диалоговом окне файла, она должна начать воспроизведение песни, а индикатор выполнения и ползунок должны начните двигаться вместе с песней, также я могу изменить ползунок, и песня должна воспроизводиться оттуда, и индикатор выполнения также должен начать двигаться оттуда, где находится ползунок.
У меня есть этот код C#. но он воспроизводит песню оттуда, где находится слайдер, но проблема в том, когда я меняю ползунок, индикатор выполнения начинает работать намного быстрее, чем песня и ползунок, и сильно продвигается вперед, когда я даже не касаюсь ползунка, но он все равно движется быстрее, чем песня и ползунок:
public MainWindow()
{
InitializeComponent();
mediaElement.LoadedBehavior = MediaState.Manual;

mediaElement.MediaOpened += MediaElement_MediaOpened;
CompositionTarget.Rendering += CompositionTarget_Rendering;
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(100);
timer.Tick += Timer_Tick;
}

private void PlayButton(object sender, RoutedEventArgs e)
{
var dialog = new Microsoft.Win32.OpenFileDialog
{
FileName = "Music", // Default file name
DefaultExt = ".mp3", // Default file extension
Filter = "Audio Files (.mp3)|*.mp3"
};

bool? result = dialog.ShowDialog();

if (result == true)
{
// Open document
string filename = dialog.FileName;
mediaElement.Source = new Uri(filename, UriKind.RelativeOrAbsolute);
mediaElement.Play();
}
}

private void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
// Check if the media has a valid duration
if (mediaElement.NaturalDuration.HasTimeSpan)
{
// Set the maximum value of the slider to the total duration of the media
slider.Maximum = mediaElement.NaturalDuration.TimeSpan.TotalSeconds;

// Update the progress bar and slider based on the current position of the media
progressBar.Value = 0;
slider.Value = 0;

// Start the timer after media is opened
timer.Start();
}
}

private void CompositionTarget_Rendering(object sender, EventArgs e)
{
if (!isDraggingSlider)
{
double currentPosition = mediaElement.Position.TotalSeconds;

progressBar.Value = currentPosition;
slider.Value = currentPosition;
}

// Check if the media has finished playing
if (mediaElement.Position >= mediaElement.NaturalDuration)
{
// Stop the rendering event when the media completes
CompositionTarget.Rendering -= CompositionTarget_Rendering;
}
}

private void Timer_Tick(object sender, EventArgs e)
{
// Update the progress bar and slider based on the current position of the media
if (!isDraggingSlider)
{
double currentPosition = mediaElement.Position.TotalSeconds;

progressBar.Value = currentPosition;
slider.Value = currentPosition;
}

// Check if the media has finished playing
if (mediaElement.Position >= mediaElement.NaturalDuration)
{
// Stop the timer when the media completes
timer.Stop();
}
}

private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e)
{
// Update the media position when the slider value changes
if (!isDraggingSlider)
{
mediaElement.Position = TimeSpan.FromSeconds(slider.Value);
}
}

private void Slider_DragStarted(object sender, RoutedEventArgs e)
{
// Pause the rendering event when the user starts dragging the slider
isDraggingSlider = true;
}

private void Slider_DragCompleted(object sender, RoutedEventArgs e)
{
// Resume the rendering event when the user finishes dragging the slider
isDraggingSlider = false;
}
}
``` I hope you understand what i'm trying to do because this is my first question

I want to make the song play according to the slider and the progress bar should follow the slider and when i change the slider the song should play form that duration just like that VLC has that slider


Подробнее здесь: https://stackoverflow.com/questions/779 ... player-wpf
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»