static void Main() { int j = 0; //using (StreamReader sr = new StreamReader(@"c:\radio_stations.csv")) //{ // int j = 0; // while (!sr.EndOfStream) // { // string line = sr.ReadLine(); // string[] fields = line.Split(",".ToCharArray()); // int i = 0; // string url = fields[i++]; // string title = fields[i++]; // string genre = fields[i++]; // RadioStation rs = new RadioStation(); // rs.Url = url; // rs.Title = title; // rs.Genre = genre; // Console.WriteLine(">> {0} / {1}", j++, 857); // ValidateUrl(url, title, genre); // } // data.SavePersistentList(); //} data = RadioStationsData.Load(); foreach (RadioStation rs in data.RadioStations) { Console.WriteLine(">> {0} / {1}", j++, data.RadioStations.Count); Console.WriteLine("Trying url: {0}", rs.Url); try { ShoutcastStream ss = new ShoutcastStream(rs.Url, 500); if (ss.Connected) { if (ss.Bitrate >= 128) { data2.RadioStations.Add(rs); } } } catch { } data2.SavePersistentList(); } string xml = PersistenceProxy.ReadObject("RadioStationsData", string.Empty); using (StreamWriter sw = new StreamWriter(@"c:\radio_stations.xml")) { sw.Write(xml); } }
public void PlayRadio(string url) { if (_oldPlayer != null) { _oldPlayer.VolumeDownAndStop(); _oldPlayer = null; } if (!string.IsNullOrEmpty(url)) { _oldPlayer = _temp; _temp = new StreamPlayer(this); _temp.OnError += _temp_OnError; _temp.OnStartPlay += _temp_OnStartPlay; _temp.OnStoped += _temp_OnStoped; ShoutcastStream s = new ShoutcastStream(url); s.StreamTitleChanged += (a, b) => { if (OnTrack != null) { OnTrack(((ShoutcastStream)a).StreamTitle); } }; _temp.Play(s); //OnTrack } _radioUrl = url; }
protected override HRESULT CheckFile() { _stream = new ShoutcastStream(m_sFileName, 4000, false); if (_stream != null && _stream.Connected) { return(S_OK); } return(S_FALSE); }
/// <summary> /// Cleans up all associated streaming resources. /// </summary> private void CleanupAudioStream() { var tempStream = this.audioStream; this.audioStream = null; if (tempStream != null) { tempStream.Closed += (s, e) => { this.OnClosed(); }; tempStream.Dispose(); } }
protected MediaFileInfo(string path, bool throwExceptionOnInvalid) : base(path, false) { this.IsServerURI = false; Uri uri = new Uri(path, UriKind.Absolute); if (uri.IsFile) { if (System.IO.File.Exists(path) == false) { throw new FileNotFoundException("File not found: " + PathUtils.GetFileName(path)); } // The path is a file. Not an actual URI ... this.IsServerURI = false; } else { _uri = path; if (path.StartsWith("dzmedia:///track/")) { // The path represents a resource on a Deezer server this.IsServerURI = true; } else { string ext = PathUtils.GetExtension(path); if (MediaRenderer.AllMediaTypes.Contains(ext)) { // This is an URI of supported type. It could be a non-server URI // but we are not sure on this. Let's check ... using (ShoutcastStream ss = new ShoutcastStream(path, 4000, true)) { this.IsServerURI = ss.Connected; } } else { // This is an URI of an unsupported type. Assume it is a server URI. this.IsServerURI = true; } } } BuildFields(path); }
public override async Task TryConnectAsync(StationStream stream) { try { streamSource = await ShoutcastStreamFactory.ConnectAsync(stream.StreamUrl, new ShoutcastStreamFactoryConnectionSettings() { UserAgent = "Neptunium (http://github.com/Amrykid/Neptunium)", RelativePath = stream.RelativePath, RequestSongMetdata = stream.RequestMetadata }); streamSource.Reconnected += StreamSource_Reconnected; streamSource.MetadataChanged += ShoutcastStream_MetadataChanged; StreamMediaSource = MediaSource.CreateFromMediaStreamSource(streamSource.MediaStreamSource); StreamMediaSource.StateChanged += StreamMediaSource_StateChanged; this.StationPlaying = await NepApp.Stations.GetStationByNameAsync(stream.ParentStation); ShoutcastStationInfo = streamSource.StationInfo; RaiseStationInfoAcquired(streamSource.StationInfo); } catch (Exception ex) { if (ex is System.Runtime.InteropServices.COMException) { if (ex.HResult == -2147014836) { /* A connection attempt failed because the connected party did not properly respond after a period of time, or * established connection failed because connected host has failed to respond. */ //At this point, we've already timed out and informed the user. We can use return out of this. return; } } throw new Neptunium.Core.NeptuniumStreamConnectionFailedException(stream, ex); } }
private static void ValidateUrl(string url, string title, string genre) { Console.WriteLine("Trying url: {0}", url); try { Uri uri = new Uri(url); string hostName = uri.DnsSafeHost; //if (!QueryDnsWithTimeout(hostName, 300)) //{ // Console.WriteLine("\t -> Url: {0} is not valid (DNS error)", url); // return; //} List <String> urlsToCkeck = new List <string>(); if (IsPlaylist(url)) { string fileName = Path.GetFileName(uri.LocalPath); string tempFile = @"c:\temp.pls"; using (WebClientWithTimeout wc = new WebClientWithTimeout()) { wc.Timeout = 500; wc.Proxy = AppSettings.GetWebProxy(); wc.DownloadFile(uri, tempFile); } if (File.Exists(tempFile)) { Playlist p = new Playlist(); p.LoadPlaylist(tempFile); File.Delete(tempFile); foreach (PlaylistItem item in p.AllItems) { urlsToCkeck.Add(item.Path); } } } else { urlsToCkeck.Add(url); } foreach (string url2 in urlsToCkeck) { //if (!QueryDnsWithTimeout(url2, 300)) // continue; ShoutcastStream ss = new ShoutcastStream(url2, 500); if (ss.Connected) { RadioStation rs = new RadioStation { Genre = genre, Title = title, Url = url2 }; data.RadioStations.Add(rs); Console.WriteLine("\t -> Added radio station: {0}", url2); ss.Close(); ss.Dispose(); ss = null; } } } catch (Exception ex) { Console.WriteLine("\t ->" + ex.Message); } Console.WriteLine("\t -> Url: {0} is not valid", url); }
public void SetRenderFile(string file) { try { _hasRenderingErrors = false; // Select the proper renderer for the specified media Uri uri = null; try { uri = new Uri(file, UriKind.Absolute); } catch { uri = null; } if (uri != null && !uri.IsFile) { if (uri.OriginalString.StartsWith("dzmedia:///track/")) { CreateNewRenderer <DeezerRenderer>(); } else { using (ShoutcastStream ss = new ShoutcastStream(file, 4000, false)) { if (ss.Connected) { CreateNewRenderer <DSShoutcastRenderer>(); } else { // Media file exposed as URL CreateNewRenderer <DSFileRenderer>(); } } } } else { if (DvdMedia.FromPath(file) != null) { CreateNewRenderer <DSDvdRenderer>(); } else { string streamType = PathUtils.GetExtension(file).ToLowerInvariant(); if (streamType == "cda") { CreateNewRenderer <DSAudioCDRenderer>(); } else { CreateNewRenderer <DSFileRenderer>(); } } } Logger.LogTrace("Now playing media: {0}", file); if (streamRenderer != null) { streamRenderer.RenderRegion = renderPanel; if (this.FilterState == OPMedia.Runtime.ProTONE.Rendering.DS.BaseClasses.FilterState.Stopped) { streamRenderer.RenderMediaName = file; } } } catch (Exception ex) { ReportRenderingException(ex); } }
private void StreamMP3_New(object state) { Thread.CurrentThread.Name = state.ToString(); string url = (string)state; byte[] buffer = new byte[16384 * 4]; Dictionary <int, IMp3FrameDecompressor> Decompressors = new Dictionary <int, IMp3FrameDecompressor>(); WaveFormat outputFormat = new WaveFormat(44100, 16, 2); this.bufferedWaveProvider = new BufferedWaveProvider(outputFormat); this.bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(2); // WaveToSampleProvider wav2sample = new WaveToSampleProvider(this.bufferedWaveProvider); ISampleProvider sampleProvider = new Pcm16BitToSampleProvider(this.bufferedWaveProvider); SampleAggregator sa = new SampleAggregator(128); sa.NotificationCount = 882; sa.PerformFFT = true; sa.FftCalculated += sa_FftCalculated; NotifyingSampleProvider notifyProvider = new NotifyingSampleProvider(sampleProvider); notifyProvider.Sample += (a, b) => sa.Add(b.Left); volumeProvider = new VolumeSampleProvider(notifyProvider); //volumeProvider = new SampleChannel(this.bufferedWaveProvider, true); volumeProvider.Volume = 0.0f; //volumeProvider.PreVolumeMeter += waveChannel_PreVolumeMeter; for (int j = 0; j < 5; ++j) { try { using (IWavePlayer waveOut = new WaveOut()) { waveOut.PlaybackStopped += waveOut_PlaybackStopped; waveOut.Init(volumeProvider); using (var readFullyStream = new ShoutcastStream(url)) { waveOut.Play(); if (OnStartPlay != null) { OnStartPlay(this); } do { if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4) { int x = 0; while (playbackState != StreamingPlaybackState.Stopped && x < 5) { x++; Thread.Sleep(50); } } else { Mp3Frame frame = Mp3Frame.LoadFromStream(readFullyStream, true); if (currentTrack != readFullyStream.StreamTitle) { currentTrack = readFullyStream.StreamTitle; if (!string.IsNullOrEmpty(currentTrack)) { ThreadPool.QueueUserWorkItem(Search, currentTrack); } else { CurrentTrack = null; if (OnNewTrack != null) { OnNewTrack(this, null); } } } IMp3FrameDecompressor dec; if (!Decompressors.TryGetValue(frame.SampleRate, out dec)) { WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate); var suggFromat = AcmStream.SuggestPcmFormat(waveFormat); dec = new VbrAcmMp3FrameDecompressor(waveFormat, outputFormat); Decompressors[frame.SampleRate] = dec; } int decompressed = dec.DecompressFrame(frame, buffer, 0); bufferedWaveProvider.AddSamples(buffer, 0, decompressed); } } while (playbackState != StreamingPlaybackState.Stopped); waveOut.Stop(); } } return; } catch (Exception exe) { int x = 0; while (playbackState != StreamingPlaybackState.Stopped && x < 20) { x++; Thread.Sleep(50); } if (playbackState == StreamingPlaybackState.Stopped) { return; } } finally { foreach (var dc in Decompressors) { dc.Value.Dispose(); } Decompressors.Clear(); } } if (OnError != null) { OnError(this); } }
/// <summary> /// Parses the passed in MediaStream to find the first frame and signals /// to its parent MediaElement that it is ready to begin playback by calling /// ReportOpenMediaCompleted. /// </summary> protected override void OpenMediaAsync() { System.Diagnostics.Debug.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + ": OpenMediaAsync()"); // So, here is why this is a little weird. // The Shoutcast server software has the ability to provide web pages. These pages just happen to be served from the SAME address as the media stream. // Putting a "/;" at the end of the Uri will tell the Shoutcast server that we aren't a web browser, so stream the data. The problem is that not ALL // Shoutcast servers are configured that way. So, we have to do a request to get the content type. If it is text/html, we append the "/;" and move on. // If it is an empty string, 99.9% of the time, this will be the media stream (If it's an ICY stream, the ICY "headers" don't parse properly). The ShoutcastStream // will handle this case, so we let it go through. HttpWebRequest contentTypeRequest = ShoutcastMediaStreamSource.CreateHttpWebRequest(this.StreamUri, this.IncludeMetadata); contentTypeRequest.BeginGetResponse( ia1 => { HttpWebRequest req1 = ia1.AsyncState as HttpWebRequest; try { HttpWebResponse res1 = (HttpWebResponse)req1.EndGetResponse(ia1); string contentType = res1.ContentType; if ((contentType == string.Empty) || (contentType == "audio/mpeg") || contentType == "audio/x-mpegurl") { try { this.audioStream = new ShoutcastStream(this, res1); this.audioStreamDescription = this.audioStream.AudioStreamDescription; this.ReportOpenMediaCompleted(this.audioStream.AudioSourceAttributes, new MediaStreamDescription[] { this.audioStream.AudioStreamDescription }); } catch (Exception ex) { this.CleanupAudioStream(); this.ErrorOccurred(ex.Message); } } else { // Close the original response. We need another one. res1.Close(); res1 = null; if (!this.StreamUri.OriginalString.EndsWith("/", StringComparison.Ordinal)) { this.StreamUri = new Uri(this.StreamUri.OriginalString + "/;", UriKind.Absolute); } else { this.StreamUri = new Uri(this.StreamUri.OriginalString + ";", UriKind.Absolute); } HttpWebRequest streamRequest = ShoutcastMediaStreamSource.CreateHttpWebRequest(this.StreamUri, this.IncludeMetadata); streamRequest.BeginGetResponse( ia => { HttpWebRequest req = ia.AsyncState as HttpWebRequest; try { HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(ia); this.audioStream = new ShoutcastStream(this, res); this.audioStreamDescription = this.audioStream.AudioStreamDescription; this.ReportOpenMediaCompleted(this.audioStream.AudioSourceAttributes, new MediaStreamDescription[] { this.audioStream.AudioStreamDescription }); } catch (Exception ex) { if (res1 != null) { res1.Close(); } this.CleanupAudioStream(); this.ErrorOccurred(ex.Message); } }, streamRequest); } } catch (Exception ex) { this.CleanupAudioStream(); this.ErrorOccurred(ex.Message); } }, contentTypeRequest); }
public override PacketData GetNextPacket() { ShoutcastStream ss = (m_pParser as ShoutcastStreamParser).ShoutcastStream; string contentType = ss.ContentType; Logger.LogTrace("ShoutcastStreamTrack::GetNextPacket contentType={0}", ss.ContentType); int slice = ss.Bitrate * 1024 / 8; PacketData dataToReturn = null; PacketData dataToRead = new PacketData(); dataToRead.Buffer = new byte[slice]; int bytesRead = ss.Read(dataToRead.Buffer, 0, slice); if (bytesRead > 0) { Logger.LogTrace("ShoutcastStreamTrack::GetNextPacket contentType={0} bytesRead={1}", ss.ContentType, bytesRead); switch (contentType) { case "audio/mpg": case "audio/mpeg": { // The data that was read has mp3 format // Since we initialized the media subtype as MPEG1Audio, it's safe to send this data directly // to the output renderer. dataToRead.Position = 0; dataToRead.Size = (int)bytesRead; dataToRead.SyncPoint = true; dataToRead.Start = m_rtMediaPosition; dataToRead.Stop = dataToRead.Start + UNITS / 2; m_rtMediaPosition = dataToRead.Stop; dataToReturn = dataToRead; } break; //case "audio/aac": //case "audio/aacp": // { // try // { // // The data that was read has ac3 format // // Since we initialized the media subtype as PCM, we'll need to convert the AC3 data // // to WAV before sending to the output renderer. // string aacFile = PathUtils.GetTempFilePath("shoutcast_in.aac"); // string wavFile = PathUtils.GetTempFilePath("shoutcast_out.wav"); // File.WriteAllBytes(aacFile, dataToRead.Buffer); // string aacFileUrl = string.Format(@"file:///{0}", aacFile.Replace("\\", "/")); // using (var reader = new MediaFoundationReader(aacFileUrl)) // WaveFileWriter.CreateWaveFile(wavFile, reader); // WaveFormatEx wfex = WaveFormatEx.Cdda; // byte[] buff = WaveFile.ReadWaveData(wavFile, ref wfex); // dataToRead.Position = 0; // dataToRead.Size = buff.Length; // dataToRead.SyncPoint = true; // dataToRead.Start = m_rtMediaPosition; // dataToRead.Stop = dataToRead.Start + UNITS; // m_rtMediaPosition = dataToRead.Stop; // dataToReturn = new PacketData(); // dataToReturn.Buffer = new byte[buff.Length]; // Array.Copy(buff, dataToReturn.Buffer, buff.Length); // } // catch (Exception ex) // { // Logger.LogTrace("ShoutcastStreamTrack: " + ex.ToString()); // } // } // break; } } Logger.LogTrace("ShoutcastStreamTrack::GetNextPacket contentType={0} returning {1}null", ss.ContentType, (dataToReturn == null) ? string.Empty : "non-"); return(dataToReturn); }