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;
InitializeComponent();
// Varsayılan bir çalma listesini yükle
waveOutEvent.PlaybackStopped += OnPlaybackStopped;
LoadPlaylistVideosAsync("RDCLAK5uy_ncwbM766_rhOk_JllLnAXmv_5v21_b2bc");
}
private async Task LoadPlaylistVideosAsync(string playlistId)
{
// UI elementlerini devre dışı bırak
PreviousButton.IsEnabled = false;
NextButton.IsEnabled = false;
PlayButton.IsEnabled = false;
ProgressProgressBar.IsEnabled = false;
RepeatButton.IsEnabled = false;
MyCollection.Clear();
// 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;
}
}
[Obsolete]
private async void SearchButton_Click(object sender, RoutedEventArgs e)
{
string text = SearchTextBox.Text.Trim();
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;
Dispatcher.Invoke(() => MyCollection.Clear());
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<Video> _myCollection = new ObservableCollection<Video>();
public ObservableCollection<Video> 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);
if (waveOutEvent.PlaybackState == PlaybackState.Playing)
{
waveOutEvent.Pause();
PlayButton.Content = "\ue102";
}
else
{
waveOutEvent.Play();
PlayButton.Content = "\ue103";
}
}
}
private void OnPlaybackStopped(object sender, StoppedEventArgs e)
{
if (repeatSong)
{
waveOutEvent.Play();
}
}
private void RepeatButton_Click(object sender, RoutedEventArgs e)
{
repeatSong = !repeatSong; // Bayrağı değiştirin
}
private async void PlayButton_Click(object sender, RoutedEventArgs e)
{
if (waveOutEvent.PlaybackState == PlaybackState.Playing)
{
waveOutEvent.Pause();
PlayButton.Content = "\ue102";
}
else
{
await PlayCurrentVideoAsync();
}
}
private async Task PlayCurrentVideoAsync()
{
if (currentVideo != null && currentVideo.AudioStreamInfo != null)
{
if (waveOutEvent != null)
{
waveOutEvent.Stop();
}
// 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;
private async void NextButton_Click(object sender, RoutedEventArgs e)
{
if (MyCollection.Count == 0) return;
var currentIndex = MyCollection.IndexOf(currentVideo);
var nextIndex = (currentIndex + 1) % MyCollection.Count;
var nextVideo = MyCollection[nextIndex];
await SelectAndPlayVideoAsync(nextVideo);
}
private async Task SelectAndPlayVideoAsync(Video video)
{
listView.SelectedItem = video;
// Bu adımı asenkron olarak yeniden düzenleyin
await PlayCurrentVideoAsync();
}
private async void PreviousButton_Click(object sender, RoutedEventArgs e)
{
if (MyCollection.Count == 0) return;
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<Video> 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();
MyCollection.Add(new Video
{
Id = videoPlaylistResult.Id,
Title = videoPlaylistResult.Title,
Author = videoPlaylistResult.Author.Title,
ThumbnailUrl = videoPlaylistResult.Thumbnails.GetWithHighestResolution()?.Url,
Duration = videoPlaylistResult.Duration.ToString(),
Likes = (int)videoDetails.Engagement.LikeCount, // Beğeni sayısını ayarla
ViewCount = (int)videoDetails.Engagement.ViewCount, // Beğenmeme sayısını ayarla
StreamUrl = audioStreamInfo?.Url, // Akış URL'sini ayarla
AudioStreamInfo = audioStreamInfo// Akış URL'sini ayarla
});
}
finally
{
semaphore.Release(); // Release the slot
}
}
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;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Öncelikle, koddaki gereksiz veya kullanılmayan bölümleri ayıklamadan önce, şunları not edelim:
- Bu kod WPF uygulaması için yazılmış görünüyor ve bir arayüz/ViewModel yapısına sahip.
YoutubeExplode kütüphanesi kullanılıyor ve YouTube verileri ile ilgili işlemler yapılıyor.
NAudio kütüphanesi kullanılıyor ve ses oynatma işlemleri gerçekleştiriliyor.
Kodu inceledikten sonra, performans iyileştirme ve temizleme adımlarını şu şekilde listeleyebilirim:
-
Kullanılmayan Using Ifadeleri:
System.Diagnostics ve System.IO namespace'leri bu kodda hiçbir yerde kullanılmıyor gibi görünüyor. Eğer gerçekten kullanılmıyorsa kaldırılabilirler.
-
DispatcherTimer:
DispatcherTimer nesnesi tanımlanmış (timer) ancak herhangi bir yere atanmadığı veya kullanılmadığı anlaşılıyor. Eğer zamanla ilgili bir işlem yapılmıyorsa bu nesne kaldırılabilir.
-
SemaphoreSlim Başlatma:
- Yorum “Max 5 concurrent detail requests” diyor ama
SemaphoreSlim 8 olarak başlatılmış. Hangi sayının doğru olduğunu kontrol et ve ihtiyacına göre düzelt.
-
Listview_SelectionChanged:
ListView_SelectionChanged metodunda birçok initializasyon işlemi yapıyor. Ancak, bunlar herhangi bir item seçildiğinde tekrar tekrar yapılıyor. Bu işlemleri sadece gerekli olduğunda yapacak şekilde optimize edebilirsiniz.
-
[Obsolete] Kullanımı:
SearchButton_Click metodu [Obsolete] attribute'u taşıyor, bu metodu yeniden gözden geçirin ve eğer uygulamanızın bu kısmı artık kullanılmıyor veya güncellenmiş bir yöntemle değiştirildi ise bu metodun tamamını kaldırabilirsiniz.
-
CancellationTokenSource (cts) Kullanımı:
cts her SearchButton_Click ve LoadPlaylistVideosAsync çağrısında yeniden oluşturuluyor gibi gözüküyor. Eğer mevcut cts değişkeni başka bir yerde kullanılmıyorsa her seferinde yeni bir CancellationTokenSource oluşturmak yerine, mevcut cts'yi iptal ederek ve Dispose ederek tekrar kullanabilirsiniz.
-
Property Change Notification:
Video class'ındaki Likes ve ViewCount property'leri her set işleminde OnPropertyChanged methodunu tetikliyor. Bu iki property çok sık değişmiyorsa veya UI'da sürekli güncellenmiyorsa, bu çağrılar gereksiz olabilir.
-
GetVideoDetailsAsync Metodları:
GetVideoDetailsAsync için iki farklı overload var, birisi VideoSearchResult ve diğeri PlaylistVideo tipinde parametre alıyor. Eğer PlaylistVideo için olan overload hiçbir yerde kullanılmıyorsa kaldırılabilir.
-
Kod Tebrikleri:
- Eğer bir parçanın yeniden kullanılabilir olduğunu ve başka yerlerde de kullanılacağını düşünüyorsanız, kod tekrarını azaltmak adına bu kod bloklarını metodlar haline getirebilirsiniz. Örneğin,
ListView_SelectionChanged ve PlayCurrentVideoAsync metodlarındaki audio stream initializasyonu ortak bir metodda birleştirilebilir.
-
Gereksiz UI Enabled Ayarlamaları:
- Bütün UI kontrollerini (
PreviousButton, NextButton, vb.) her seçim değişikliğinde true yapıyorsunuz. Bunun yerine bir kontrolün değerini gereksiz yere değiştirmemeyi tercih edebilirsiniz.
Son olarak, bu optimizasyonları uygularken kodun diğer kısımları ile entegre şekilde çalıştığından emin olunuz ve her değişiklik sonrası uygulamanın beklenildiği gibi davranıp davranmadığını test ediniz.
Bu değişikliklerle artık her yeni CancellationTokenSource yaratmadan önce mevcut olanı uygun şekilde iptal edip kaynaklarını serbest bırakıyoruz. Bu küçük değişiklik, uygulamanın performansını ve kaynak yönetimini geliştirecektir. Yeni ResetCancellationTokenSource metodu sayesinde kodunuzu da daha bakımı kolay hale getirebilirsiniz. Unutmayın ki bu değişikliklerden sonra uygulamanızın hala beklediğiniz gibi çalışıp çalışmadığını test etmelisiniz.