using System;
using System.Windows.Forms;
using Alvas.Audio;
using System.IO;
using System.Threading;
namespace RadioCs
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
FormClosed += Form1_FormClosed;
btnPlay.Click += btnPlay_Click;
btnStop.Click += btnStop_Click;
}
private void btnPlay_Click(System.Object sender, System.EventArgs e)
{
ReadRadio("http://www.wmph.org:7050/wmph64k");
}
private void btnStop_Click(System.Object sender, System.EventArgs e)
{
if ((t != null) && t.ThreadState == ThreadState.Running)
{
t.Abort();
btnStop.Enabled = false;
btnPlay.Enabled = true;
}
}
private PlayerEx plex = new Alvas.Audio.PlayerEx(true);
private System.Threading.Thread t;
private void ReadRadio(string StreamURL)
{
btnStop.Enabled = true;
btnPlay.Enabled = false;
t = new Thread(new ParameterizedThreadStart(ThreadProc));
t.Start(StreamURL);
}
private void ThreadProc(object StreamURL)
{
System.Net.HttpWebRequest WebReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(StreamURL.ToString());
Uri MyURI = new Uri(StreamURL.ToString());
WebReq.Headers.Clear();
WebReq.Timeout = 5000;
WebReq.Headers.Add("GET", MyURI.AbsolutePath + " HTTP/1.0");
WebReq.UserAgent = "WinampMPEG/5.0";
WebReq.Headers.Add("Icy-MetaData", "1");
System.Net.WebResponse WebRes = WebReq.GetResponse();
System.IO.Stream oReader = WebRes.GetResponseStream();
int MetaInterval = Int32.Parse(WebRes.Headers["icy-metaint"]);
byte[] data = new byte[MetaInterval];
byte b = 0;
Mp3Writer mw = new Mp3Writer(File.Create("out.mp3"));
int BlockCount = 0;
try
{
while (true)
{
b = (byte)oReader.ReadByte();
if (BlockCount == MetaInterval)
{
//Metadata loop
mw.WriteData(data);
if (plex.State == DeviceState.Closed)
{
Mp3Reader mr = new Mp3Reader(new MemoryStream(data));
IntPtr format = mr.ReadFormat();
mr.Close();
plex.OpenPlayer(format);
plex.StartPlay();
}
plex.AddData(data);
int MetaDataLength = b * 16;
if (MetaDataLength > 0)
{
byte[] MetaArray = new byte[MetaDataLength];
oReader.Read(MetaArray, 0, MetaDataLength);
System.Text.ASCIIEncoding AEnc = new System.Text.ASCIIEncoding();
string TempMetaData = AEnc.GetString(MetaArray);
//Trim it down
int StartPosition = TempMetaData.IndexOf("'") + 1;
int EndPosition = TempMetaData.IndexOf("';", StartPosition);
TempMetaData = TempMetaData.Substring(StartPosition, EndPosition - StartPosition);
Console.WriteLine(TempMetaData);
}
BlockCount = 0;
continue;
}
else
{
data[BlockCount] = b;
}
BlockCount = BlockCount + 1;
}
}
finally
{
oReader.Close();
mw.Close();
plex.ClosePlayer();
}
}
private void Form1_FormClosed(System.Object sender, System.Windows.Forms.FormClosedEventArgs e)
{
btnStop.PerformClick();
}
}
}