Feedback

C# - Internet Stream aufzeichnen mit C#

Veröffentlicht von am 6/19/2011
(1 Bewertungen)
Mit dieser Klasse lassen sich Internet Streams aufzeichnen und in eine Datei speichern.

Wichtig dabei ist die Konfig folgendermaßen zu ergänzen:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
</configuration>


Diese Ergänzung der Konfig ermöglicht es Streams mit unsicherem Header aufzuzeichnen.
class RadioStream
{
	public RadioStream(string streamingUrl, string fullFilename)
	{
		webRequest = WebRequest.Create(streamingUrl);
		this.FullFilename = fullFilename;
	}

	public string FullFilename { get; set; }

	WebRequest webRequest;
	WebResponse webResponse;
	BufferedStream bufferedStream;


	public bool IsRecording;
	private bool stopped = true;

	public delegate void RecordingStartedEventhandler();
	public event RecordingStartedEventhandler RecordingStarted;

	public delegate void RecordingStoppedEventhandler();
	public event RecordingStoppedEventhandler RecordingStopped;

	public delegate void RecordingProgressChangedEventhandler(object sender, RecordingEventArgs args);
	public event RecordingProgressChangedEventhandler RecordingProgressChanged;

	public void StartRecording()
	{
		stopped = false;
		IsRecording = true;

		webResponse = webRequest.GetResponse();

		bufferedStream = new BufferedStream(webResponse.GetResponseStream());

		using (FileStream outputStream = new FileStream(this.FullFilename, FileMode.Create, FileAccess.Write))
		{
			int cnt = 0;
			const int LEN = 9;
			byte[] buffer = new byte[LEN];

			while ((cnt = bufferedStream.Read(buffer, 0, LEN)) != 0)
			{
				if (stopped == true)
				{
					break;
				}

				outputStream.Write(buffer, 0, cnt);

				RecordingProgressChanged(this, new RecordingEventArgs(outputStream.Length));
			}
		}

		if (RecordingStarted != null)
		{
			RecordingStarted();
		}
	}

	public void StopRecording()
	{
		stopped = true;
		IsRecording = false;

		if (RecordingStopped != null)
		{
			RecordingStopped();
		}
	}
}

public class RecordingEventArgs : EventArgs
{
	public long StreamLength { get; set; }

	public RecordingEventArgs(long streamLength)
	{
		this.StreamLength = streamLength;
	}
}

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!