private async Task CheckPrebufferingAsync(Stream inStream, SongBuffer sb, CancellationToken cancelToken) { while (!sb.BufferingCompleted && inStream.Length < 2.MiB()) { await Task.Delay(100, cancelToken); } Console.WriteLine("Buffering successfull"); }
internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken) { var filename = Path.Combine(MusicModule.MusicDataPath, DateTime.Now.UnixTimestamp().ToString()); SongBuffer sb = new SongBuffer(filename, SongInfo, skipTo); var bufferTask = sb.BufferSong(cancelToken).ConfigureAwait(false); var inStream = new FileStream(sb.GetNextFile(), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Write);; bytesSent = 0; try { var attempt = 0; var prebufferingTask = CheckPrebufferingAsync(inStream, sb, cancelToken); var sw = new Stopwatch(); sw.Start(); var t = await Task.WhenAny(prebufferingTask, Task.Delay(5000, cancelToken)); if (t != prebufferingTask) { Console.WriteLine("Prebuffering timed out or canceled. Cannot get any data from the stream."); return; } else if (prebufferingTask.IsCanceled) { Console.WriteLine("Prebuffering timed out. Cannot get any data from the stream."); return; } sw.Stop(); Console.WriteLine("Prebuffering successfully completed in " + sw.Elapsed); const int blockSize = 3840; byte[] buffer = new byte[blockSize]; while (!cancelToken.IsCancellationRequested) { //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------"); var read = inStream.Read(buffer, 0, buffer.Length); //await inStream.CopyToAsync(voiceClient.OutputStream); unchecked { bytesSent += (ulong)read; } if (read < blockSize) { if (sb.IsNextFileReady()) { inStream.Dispose(); inStream = new FileStream(sb.GetNextFile(), FileMode.Open, FileAccess.Read, FileShare.Write); read += inStream.Read(buffer, read, buffer.Length - read); attempt = 0; } if (read == 0) { if (sb.BufferingCompleted) { break; } if (attempt++ == 20) { voiceClient.Wait(); MusicPlayer.SongCancelSource.Cancel(); break; } else { await Task.Delay(100, cancelToken).ConfigureAwait(false); } } else { attempt = 0; } } else { attempt = 0; } while (this.MusicPlayer.Paused) { await Task.Delay(200, cancelToken).ConfigureAwait(false); } buffer = AdjustVolume(buffer, MusicPlayer.Volume); voiceClient.Send(buffer, 0, read); } } finally { await bufferTask; await Task.Run(() => voiceClient.Clear()); if (inStream != null) { inStream.Dispose(); } Console.WriteLine("l"); sb.CleanFiles(); } }