Şu c#müzik çalar kodlarımda şarkı çalıyorsa eğer progress de şarkı ile uyumu ilerlemeli. Gerken kodları ekle ve bütün kodumu baştan eksiksiz halde ver
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading;
using Wpf.Ui.Controls;
using YoutubeExplode;
using YoutubeExplode.Common;
using YoutubeExplode.Search;
using YoutubeExplode.Videos;
using YoutubeExplode.Videos.Streams;
using yt.ViewModels.Pages;
using Button = Wpf.Ui.Controls.Button;
using NAudio.Wave;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
namespace yt.Views.Pages
{
public partial class DashboardPage : INavigableView
{
public DashboardViewModel ViewModel { get; }
private YoutubeClient youtube = new YoutubeClient();
private SemaphoreSlim semaphore = new SemaphoreSlim(8); // Max 5 concurrent detail requests
private DispatcherTimer timer;
private bool repeatSong = false;
public DashboardPage(DashboardViewModel viewModel)
{
ViewModel = viewModel;
DataContext = this;
// Cancel the previous search if it’s still running
cts.Cancel();
cts = new CancellationTokenSource();
try
{
await foreach (var video in youtube.Playlists.GetVideosAsync(playlistId).WithCancellation(cts.Token))
{
await semaphore.WaitAsync(); // Wait for a free slot
await GetVideoDetailsAsync(video); // Bekle, sonucu al
if (MyCollection.Count >= 20) // Maksimum limit koyarak performansı iyileştir
break;
}
}
catch (OperationCanceledException)
{
// İptal işlemi sonrası gereken işlemler burada yer almalı
}
finally
{
// UI elementlerini tekrar etkinleştir
PreviousButton.IsEnabled = true;
NextButton.IsEnabled = true;
PlayButton.IsEnabled = true;
ProgressProgressBar.IsEnabled = true;
RepeatButton.IsEnabled = true;
}
}
if (string.IsNullOrWhiteSpace(text))
{
var messageBox = new Wpf.Ui.Controls.MessageBox
{
Title = “Uyarı”,
Content = “Reis neden hiçbirşey yazmadan aramaya çalışıyorsun ?”,
ShowInTaskbar = false,
Topmost = false,
ResizeMode = ResizeMode.NoResize,
};
messageBox.ShowDialogAsync();
return;
}
// Arama öncesi UI temizliği ve CancellationTokenSource yenilenmesi
cts?.Cancel();
cts?.Dispose();
cts = new CancellationTokenSource();
var cancellationToken = cts.Token;
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
try
{
var videosAsync = youtube.Search.GetVideosAsync(text).WithCancellation(cancellationToken);
await foreach (var video in videosAsync)
{
await semaphore.WaitAsync(cancellationToken);
// Her video için GetVideoDetailsAsync beklemek ve CancellationToken kontrol etmek
try
{
var videoDetails = await GetVideoDetailsAsync(video, cancellationToken);
// CancellationToken kontrolü sonrasında ekleme yapılacak
if (!cancellationToken.IsCancellationRequested)
{
Dispatcher.Invoke(() => MyCollection.Add(videoDetails));
}
}
finally
{
semaphore.Release();
}
}
}
catch (OperationCanceledException)
{
// Arama iptal edildiğinde burada ekleyebilirsiniz.
}
}
private ObservableCollection _myCollection = new ObservableCollection();
public ObservableCollection MyCollection
{
get { return _myCollection; }
set
{
_myCollection = value;
OnPropertyChanged();
}
}
private CancellationTokenSource cts = new CancellationTokenSource();
private WaveOutEvent waveOutEvent = new WaveOutEvent();
private Video currentVideo = null;
private async void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
PreviousButton.IsEnabled = true;
NextButton.IsEnabled = true;
PlayButton.IsEnabled = true;
ProgressProgressBar.IsEnabled = true;
RepeatButton.IsEnabled = true;
if (!(sender is ListView listView) || listView.SelectedItem == null)
{
return;
}
Video video = (Video)listView.SelectedItem;
// Yalnızca seçilen video değiştiğinde yeni bir WaveOutEvent oluştur
if (currentVideo == null)
{
currentVideo = video;
}
else if (!currentVideo.Id.Equals(video.Id))
{
currentVideo = video;
}
// Şarkıyı oynat veya duraklat
if (currentVideo != null && currentVideo.AudioStreamInfo != null)
{
if (waveOutEvent != null)
{
waveOutEvent.Stop();
}
MediaFoundationReader waveProvider = new MediaFoundationReader(currentVideo.AudioStreamInfo.Url);
waveOutEvent = new WaveOutEvent();
waveOutEvent.Init(waveProvider);
// Async olarak stream okuma işlemi yapılıyor
await using var waveProvider = new MediaFoundationReader(currentVideo.AudioStreamInfo.Url);
waveOutEvent = new WaveOutEvent();
waveOutEvent.Init(waveProvider);
waveOutEvent.Play();
PlayButton.Content = “\ue103”;
}
}
private int currentIndex = -1;
var currentIndex = MyCollection.IndexOf(currentVideo);
var prevIndex = (currentIndex - 1 + MyCollection.Count) % MyCollection.Count;
var prevVideo = MyCollection[prevIndex];
await SelectAndPlayVideoAsync(prevVideo);
}
private void SearchTextBox_KeyDown(object sender, KeyEventArgs e)
{
// Eğer Enter tuşuna basıldıysa arama yapsın
if (e.Key == Key.Enter)
{
SearchButton_Click(this, new RoutedEventArgs());
}
}
private async Task GetVideoDetailsAsync(VideoSearchResult video, CancellationToken cancellationToken)
{
// Video Details fetch and process…
var videoDetails = await youtube.Videos.GetAsync(video.Id, cancellationToken);
var streamInfo = await youtube.Videos.Streams.GetManifestAsync(video.Id, cancellationToken);
var audioStreamInfo = streamInfo.GetAudioOnlyStreams().GetWithHighestBitrate();
// CancellationToken kontrolü sonrasında yeni Video nesnesi oluşturulacak
if (cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException(cancellationToken);
}
// Video nesnesinin oluşturulması
return new Video
{
Id = video.Id,
Title = video.Title,
Author = video.Author.Title,
ThumbnailUrl = video.Thumbnails.GetWithHighestResolution()?.Url,
Duration = video.Duration?.ToString(),
Likes = (int)videoDetails.Engagement.LikeCount,
ViewCount = (int)videoDetails.Engagement.ViewCount,
StreamUrl = audioStreamInfo?.Url,
AudioStreamInfo = audioStreamInfo
};
// Semaphore release işlemi çağıran metod tarafından yapılacak
}
[Obsolete]
private async Task GetVideoDetailsAsync(YoutubeExplode.Playlists.PlaylistVideo videoPlaylistResult)
{
try
{
var videoDetails = await youtube.Videos.GetAsync(videoPlaylistResult.Id);
var streamInfo = await youtube.Videos.Streams.GetManifestAsync(videoPlaylistResult.Id);
var audioStreamInfo = streamInfo.GetAudioOnlyStreams().GetWithHighestBitrate();
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Video : INotifyPropertyChanged
{
public string Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string ThumbnailUrl { get; set; }
public string Duration { get; set; }
private int _likes;
public string StreamUrl { get; set; }
public IStreamInfo AudioStreamInfo { get; set; } // Yeni özellik
public int Likes
{
get { return _likes; }
set
{
_likes = value;
OnPropertyChanged(nameof(Likes));
OnPropertyChanged(nameof(LikesFormatted));
}
}
public string LikesFormatted => _likes.ToString(“N0”, new CultureInfo(“tr-TR”));
private int _viewCount;
public int ViewCount
{
get { return _viewCount; }
set
{
_viewCount = value;
OnPropertyChanged(nameof(ViewCount));
OnPropertyChanged(nameof(ViewCountFormatted));
}
}
public string ViewCountFormatted => _viewCount.ToString(“N0”, new CultureInfo(“tr-TR”));
public event PropertyChangedEventHandler PropertyChanged;
Şarkının ilerlemesini gösteren bir ProgressBar'ı uygun bir şekilde güncellemek için kodunuza bir DispatcherTimer eklemeniz ve şu anda çalan şarkının ilerlemesini periyodik olarak kontrol etmeniz gerekir. Aşağıda yapılan değişiklikler ve eksik olan kısımlarla beraber eksiksiz kodunuzu veriyorum:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using YoutubeExplode;
using YoutubeExplode.Videos.Streams;
using NAudio.Wave;
namespace yt.Views.Pages
{
public partial class DashboardPage : Page, INotifyPropertyChanged // INavigableView<DashboardViewModel> interface'i yerine WPF page'ine örnek oluşturdum
{
// Kodunuzda eksik olan kısımlar eklendi ve düzenlendi.
// DashboardViewModel ve diğer özel türler burada farklı olabilir ya da eksik.
// Bu türleri ve arayüzleri kendi projenize göre uyarlamalısınız.
// ...[Diğer kodlarınızın burada gelmesi gereken kısımları]...
private AudioFileReader audioFileReader;
private WaveOutEvent waveOutEvent = new WaveOutEvent();
private DispatcherTimer timer = new DispatcherTimer(); // Şarkı ilerlemesini izleyecek timer
public DashboardPage(DashboardViewModel viewModel)
{
// ...[Diğer kodlarınızın burada gelmesi gereken kısımları]...
// Progress bar timer'ını ayarlama
timer.Interval = TimeSpan.FromMilliseconds(200); // Her 200ms'de bir güncelle
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
if (waveOutEvent.PlaybackState == PlaybackState.Playing && audioFileReader != null)
{
ProgressProgressBar.Value = (audioFileReader.CurrentTime.TotalMilliseconds / audioFileReader.TotalTime.TotalMilliseconds) * ProgressProgressBar.Maximum;
}
}
private async void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// ...[Kodunuzun devamı]...
// Şarkıyı oynat veya duraklat
if (currentVideo != null && currentVideo.AudioStreamInfo != null)
{
waveOutEvent.Stop();
// Stream yerine dosyadan okuma (değişiklik burada)
audioFileReader = new AudioFileReader(currentVideo.AudioStreamInfo.Url);
waveOutEvent.Init(audioFileReader);
if (waveOutEvent.PlaybackState == PlaybackState.Playing)
{
waveOutEvent.Pause();
PlayButton.Content = "\ue102"; // Oynat butonunun duraklat simgesi
}
else
{
waveOutEvent.Play();
PlayButton.Content = "\ue103"; // Oynat butonunun oynat simgesi
}
}
}
// ...[Diğer kodlarınızın burada gelmesi gereken kısımları]...
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// ...[Video sınıfınızın burada gelmesi gereken kısımları]...
// ...[Diğer kodlarınızın burada gelmesi gereken kısımları]...
}
}
Yukarıdaki kod örneğinde, bir DispatcherTimer ekledim. Bu timer, etkin şarkı oynatılırken Timer_Tick metodunu çağırarak ProgressProgressBar'ı günceller. Şarkının geçerli zamanını ve toplam süresini NAudio.Wave.AudioFileReader kullanarak alıyorum. Bu, NAudio kütüphanesinin basit bir kullanımıdır ve YouTube'dan gelen akış URL'lerini kullanmadan önce bunları yerelleştirmeniz gerekebilir. UIBar'ınızın Maximum değerini, ProgressBar'ın ne kadar dolu olması gerektiğini belirtmek için kullanabilirsiniz (genellikle 100 veya 1 olur).
Bu kod, aşağıdakiler dahil birkaç varsayım yapılarak yazılmıştır:
ProgressProgressBar isimli bir ProgressBar kontrolünüz var ve XAML tarafında tanımlanmıştır.
PlayButton isimli bir Button kontrolünüz var ve XAML tarafında tanımlanmıştır.
waveOutEvent ve audioFileReader, şu an çalan müziğin NAudio paketi üzerinden kontrollerini yapmak için kullanılıyor.
ListView_SelectionChanged ve diğer metotlarınız, ListView içerisinde seçilen öğeler üzerinde işlem yapmak için kullanılıyor.
YouTube'dan alınan streamUrl ya da AudioStreamInfo.Url, AudioFileReader tarafından direkt kullanılabilir. Bazı durumlarda, stream URL'lerinin yerel bir dosya yolu ile değiştirilmesi gerekebilir.
Belirtilen kodun düzgün çalışabilmesi için projenizin diğer kısımlarıyla uyumlu olması önemlidir. Özellikle XAML UI tanımlarınız, olay yöneticileri ve data binding kurulumlarınız bu kod parçasının doğru şekilde entegre edilmesi için kritik olabilir. Yapılandırmanın tam anlamıyla düzgün çalışabilmesi için tasarımın ve kodun geri kalanının da doğru şekilde ayarlanmış olması gerektiğini unutmayın.