I have a class that will help me play mp3 files from URL sources. It works well when it plays, pauses and resumes. But I'm embarrassed to skip forward or backward.
I use temporary files to store mp3 data and I want to move the FileStream according to the position selected by the user. But there is a problem for this.
Problem: If the line item does not exist yet. (Not loaded) 
This can be solved using WebRequest.AddRange() , but in this case we must open a new FileStream to store bytes separately and call the AddRange() method each time the user wants to go forward or backward, which means that the file will be reloaded with this position. However, if this is done too often, we must download the file as much as the number forward or backward.
So, if there is a simple and quota solution, let me know. I canβt figure out how to do this. Help me please!
My code is:
public class NAudioPlayer { HttpWebRequest req; HttpWebResponse resp; Stream stream; WaveOut waveOut; Mp3WaveFormat format; AcmMp3FrameDecompressor decompressor; BufferedWaveProvider provider; FileStream tempFileStream; System.Windows.Forms.Timer ticker; private int bufferedDuration; string url, path; long size, streamPos; int timeOffset, timePosition, avgBytes, duration; bool formatKnown, waitinloop, exitloop; State currentState; public NAudioPlayer(string mp3Url) { this.url = mp3Url; this.currentState = State.Stopped; this.size = -1; this.timeOffset = 0; this.timePosition = 0; this.avgBytes = 0; this.duration = 0; this.format = null; this.ticker = new System.Windows.Forms.Timer(); this.waveOut = new WaveOut(); this.waitinloop = false; ticker.Interval = 250; ticker.Tick += ticker_Tick; } int target = 0; void ticker_Tick(object sender, EventArgs e) { if (waveOut.PlaybackState == PlaybackState.Playing) { timePosition = timeOffset + (int)(waveOut.GetPosition() * 1d / waveOut.OutputWaveFormat.AverageBytesPerSecond); Debug.WriteLine(timePosition); } if (duration != 0 && timePosition >= duration) { waveOut.Stop(); ticker.Stop(); } if (timePosition == target && timePosition < duration - 5 && provider != null && provider.BufferedDuration.TotalSeconds < 5) { waveOut.Pause(); currentState = State.Buffering; target = timePosition + 5; } if (currentState == State.Buffering && provider != null && provider.BufferedDuration.TotalSeconds >= 5) { waveOut.Play(); } } public void Play() { int range = avgBytes <= 0 ? 0 : timeOffset * avgBytes; int readBytes = 0; long pos = 0; this.streamPos = 0; exitloop = false; disposeAllResources(); ticker.Start(); Task.Run(() => {
c # audio-streaming
Ali tor
source share