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;
LoadPlaylistVideos("RDCLAK5uy_ncwbM766_rhOk_JllLnAXmv_5v21_b2bc");
}
private async void LoadPlaylistVideos(string playlistId)
{
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();
int counter = 0; // Sayaç ekleniyor
try
{
await foreach (var video in youtube.Playlists.GetVideosAsync(playlistId).WithCancellation(cts.Token))
{
await semaphore.WaitAsync(); // Wait for a free slot
_ = GetVideoDetailsAsync(video); // Fire and forget
counter++; // Her video eklendiğinde sayaç artırılıyor
if (counter >= 20) // Eğer sayaç 20'ye ulaştıysa döngüyü kır
break;
}
}
catch (OperationCanceledException)
{
}
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;
// Eğer SearchTextBox boşsa, uyarı ver ve arama yapma
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;
}
MyCollection.Clear();
var searchQuery = SearchTextBox.Text;
// Cancel the previous search if it's still running
cts.Cancel();
cts = new CancellationTokenSource();
int counter = 0; // Sayaç ekleniyor
try
{
await foreach (var video in youtube.Search.GetVideosAsync(searchQuery).WithCancellation(cts.Token))
{
await semaphore.WaitAsync(); // Wait for a free slot
_ = GetVideoDetailsAsync(video); // Fire and forget
counter++; // Her video eklendiğinde sayaç artırılıyor
if (counter >= 8) // Eğer sayaç 20'ye ulaştıysa döngüyü kır
break;
}
}
catch (OperationCanceledException)
{
}
}
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))
{
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 void PlayButton_Click(object sender, RoutedEventArgs e)
{
if (waveOutEvent.PlaybackState == PlaybackState.Playing)
{
waveOutEvent.Pause();
PlayButton.Content = "\ue102";
}
else
{
waveOutEvent.Play();
PlayButton.Content = "\ue103";
}
}
private int currentIndex = -1;
private async void NextButton_Click(object sender, RoutedEventArgs e)
{
// Get the current selected item from the ListView
var currentVideo = (Video)listView.SelectedItem;
// Find the index of the current video in the MyCollection
var currentIndex = MyCollection.IndexOf(currentVideo);
// Get the next video (wrapping around if necessary)
var nextVideo = (currentIndex == MyCollection.Count - 1) ? MyCollection[0] : MyCollection[currentIndex + 1];
// Unsubscribe from the SelectionChanged event to prevent it from firing
listView.SelectionChanged -= ListView_SelectionChanged;
// Select the next video in the ListView
listView.SelectedItem = nextVideo;
// Resubscribe to the SelectionChanged event
listView.SelectionChanged += ListView_SelectionChanged;
// Play the next video
IStreamInfo withHighestBitrate = nextVideo.AudioStreamInfo;
if (withHighestBitrate != null)
{
// Stop the current playing song
if (waveOutEvent != null)
{
waveOutEvent.Stop();
}
MediaFoundationReader waveProvider = new MediaFoundationReader(withHighestBitrate.Url);
waveOutEvent = new WaveOutEvent();
waveOutEvent.Init(waveProvider);
waveOutEvent.Play();
PlayButton.Content = "\ue103";
}
}
private async void PreviousButton_Click(object sender, RoutedEventArgs e)
{
// Get the current selected item from the ListView
var currentVideo = (Video)listView.SelectedItem;
// Find the index of the current video in the MyCollection
var currentIndex = MyCollection.IndexOf(currentVideo);
// Get the previous video (wrapping around if necessary)
var previousVideo = (currentIndex == 0) ? MyCollection[MyCollection.Count - 1] : MyCollection[currentIndex - 1];
// Unsubscribe from the SelectionChanged event to prevent it from firing
listView.SelectionChanged -= ListView_SelectionChanged;
// Select the previous video in the ListView
listView.SelectedItem = previousVideo;
// Resubscribe to the SelectionChanged event
listView.SelectionChanged += ListView_SelectionChanged;
// Play the previous video
IStreamInfo withHighestBitrate = previousVideo.AudioStreamInfo;
if (withHighestBitrate != null)
{
// Stop the current playing song
if (waveOutEvent != null)
{
waveOutEvent.Stop();
}
MediaFoundationReader waveProvider = new MediaFoundationReader(withHighestBitrate.Url);
waveOutEvent = new WaveOutEvent();
waveOutEvent.Init(waveProvider);
waveOutEvent.Play();
PlayButton.Content = "\ue103";
}
}
private async Task GetVideoDetailsAsync(VideoSearchResult video)
{
try
{
var videoDetails = await youtube.Videos.GetAsync(video.Id);
var streamInfo = await youtube.Videos.Streams.GetManifestAsync(video.Id);
var audioStreamInfo = streamInfo.GetAudioOnlyStreams().GetWithHighestBitrate();
MyCollection.Add(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, // 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
}
}
[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));
}
}
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";
}
}
}