2013-04-03 2 views
3

У меня есть этот код, он записывает запись из крика, но он разбивает его на каждый заголовок песни в другом файле. То, что я хочу, чтобы все записи в один файл и хотите точнее ПериодЗаписать крик за фиксированный период времени

public class SHOUTcastRipper 
{ 
    private SHOUTcastRipper() 
    { 
     // No objects of this class allowed 
    } 

    [STAThread] 
    static void Main() 
    { 
     // http://relay.pandora.radioabf.net:9000 
     String server = "http://radio.mosaiquefm.net:8000/mosalive"; 
     String serverPath = "/"; 

     String destPath = "A:\\";   // destination path for saved songs 

     HttpWebRequest request = null; // web request 
     HttpWebResponse response = null; // web response 

     int metaInt = 0; // blocksize of mp3 data 
     int count = 0; // byte counter 
     int metadataLength = 0; // length of metadata header 

     string metadataHeader = ""; // metadata header that contains the actual songtitle 
     string oldMetadataHeader = null; // previous metadata header, to compare with new header and find next song 

     byte[] buffer = new byte[512]; // receive buffer 

     Stream socketStream = null; // input stream on the web request 
     Stream byteOut = null; // output stream on the destination file 

     // create web request 
     request = (HttpWebRequest) WebRequest.Create(server); 

     // clear old request header and build own header to receive ICY-metadata 
     request.Headers.Clear(); 
     request.Headers.Add("GET", serverPath + " HTTP/1.0"); 
     request.Headers.Add("Icy-MetaData", "1"); // needed to receive metadata informations 
     request.UserAgent = "WinampMPEG/5.09"; 

     // execute request 
     try 
     { 
      response = (HttpWebResponse) request.GetResponse(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
      return; 
     } 

     // read blocksize to find metadata header 
     metaInt = Convert.ToInt32(response.GetResponseHeader("icy-metaint")); 

     try 
     { 
      // open stream on response 
      socketStream = response.GetResponseStream(); 

      // rip stream in an endless loop 
      while (true) 
      { 
       // read byteblock 
       int bufLen = socketStream.Read(buffer, 0, buffer.Length); 
       if (bufLen < 0) 
        return; 

       for (int i=0; i<bufLen ; i++) 
       { 
        // if there is a header, the 'headerLength' would be set to a value != 0. Then we save the header to a string 
        if (metadataLength != 0) 
        { 
         metadataHeader += Convert.ToChar(buffer[i]); 
         metadataLength--; 
         if (metadataLength == 0) // all metadata informations were written to the 'metadataHeader' string 
         { 
          string fileName = ""; 

          // if songtitle changes, create a new file 
          if (!metadataHeader.Equals(oldMetadataHeader)) 
          { 
           // flush and close old byteOut stream 
           if (byteOut != null) 
           { 
            byteOut.Flush(); 
            byteOut.Close(); 
           } 

           // extract songtitle from metadata header. Trim was needed, because some stations don't trim the songtitle 
           fileName = Regex.Match(metadataHeader, "(StreamTitle=')(.*)(';StreamUrl)").Groups[2].Value.Trim(); 

           // write new songtitle to console for information 
           Console.WriteLine(fileName); 

           // create new file with the songtitle from header and set a stream on this file 
           byteOut = createNewFile(destPath, fileName); 

           // save new header to 'oldMetadataHeader' string, to compare if there's a new song starting 
           oldMetadataHeader = metadataHeader; 
          } 
          metadataHeader = ""; 
         } 
        } 
        else // write mp3 data to file or extract metadata headerlength 
        { 
         if (count++ < metaInt) // write bytes to filestream 
         { 
          if (byteOut != null) // as long as we don't have a songtitle, we don't open a new file and don't write any bytes 
          { 
           byteOut.Write(buffer, i, 1); 
           if (count%100 == 0) 
            byteOut.Flush(); 
          } 
         } 
         else // get headerlength from lengthbyte and multiply by 16 to get correct headerlength 
         { 
          metadataLength = Convert.ToInt32(buffer[i])*16; 
          count = 0; 
         } 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
     finally 
     { 
      if (byteOut != null) 
       byteOut.Close(); 
      if (socketStream != null) 
       socketStream.Close(); 
     } 
    } 

    /// <summary> 
    /// Create new file without overwritin existing files with the same filename. 
    /// </summary> 
    /// <param name="destPath">destination path of the new file</param> 
    /// <param name="filename">filename of the file to be created</param> 
    /// <returns>an output stream on the file</returns> 
    private static Stream createNewFile(String destPath, String filename) 
    { 
     // replace characters, that are not allowed in filenames. (quick and dirrrrrty ;)) 
     filename = filename.Replace(":", ""); 
     filename = filename.Replace("/", ""); 
     filename = filename.Replace("\\", ""); 
     filename = filename.Replace("<", ""); 
     filename = filename.Replace(">", ""); 
     filename = filename.Replace("|", ""); 
     filename = filename.Replace("?", ""); 
     filename = filename.Replace("*", ""); 
     filename = filename.Replace("\"", ""); 

     try 
     { 
      // create directory, if it doesn't exist 
      if (!Directory.Exists(destPath)) 
       Directory.CreateDirectory(destPath); 

      // create new file 
      if (!File.Exists(destPath + filename + ".mp3")) 
      { 
       return File.Create(destPath + filename + ".mp3"); 
      } 
      else // if file already exists, don't overwrite it. Instead, create a new file named <filename>(i).mp3 
      { 
       for (int i=1;; i++) 
       { 
        if (!File.Exists(destPath + filename + "(" + i + ").mp3")) 
        { 
         return File.Create(destPath + filename + "(" + i + ").mp3"); 
        } 
       } 
      } 
     } 
     catch (IOException) 
     { 
      return null; 
     } 
    } 
} 

любые идеи HOWA в modifie код, чтобы сделать работу !!

+0

Что вы имеете в виду: и хотите точный период? – Siraf

+0

Я имею в виду, что я хочу записать всего за 30 минут, например – 7addan

+0

Если вы хотите записать определенное количество времени, то вам нужно знать длину каждой части mp3, верно? Вы знаете эту информацию? информация заголовка mp3-части говорит вам, как долго это происходит? Если да, то вы можете просто добавить счетчик времени к вашему коду и увеличивать его каждый раз, когда вы добавляете в него новую mp3-часть, а затем закрывать файл, когда его содержимое больше указанного времени. – Siraf

ответ

2

Я получил решение это код, если тело это нужно

public void record() 
    { 
    // http://relay.pandora.radioabf.net:9000 
    String server = "http://radio.mosaiquefm.net:8000/mosalive"; 
    String serverPath = "/"; 

    String destPath = "A:\\";   // destination path for saved songs 
    String fname="test"; 
    HttpWebRequest request = null; // web request 
    HttpWebResponse response = null; // web response 

    int metaInt = 0; // blocksize of mp3 data 
    int count = 0; // byte counter 
    int metadataLength = 0; // length of metadata header 

    byte[] buffer = new byte [ 512 ]; // receive buffer 

    Stream socketStream = null; // input stream on the web request 
    Stream byteOut = null; // output stream on the destination file 

    // create web request 
    request = (HttpWebRequest) WebRequest . Create (server); 

    // clear old request header and build own header to receive ICY-metadata 
    request . Headers . Clear (); 
    request . Headers . Add ("GET" , serverPath + " HTTP/1.0"); 
    request . Headers . Add ("Icy-MetaData" , "1"); // needed to receive metadata informations 
    request . UserAgent = "WinampMPEG/5.09"; 

    // execute request 
    try 
     { 
     response = (HttpWebResponse) request . GetResponse (); 
     } 
    catch (Exception ex) 
     { 
     Console . WriteLine (ex . Message); 
     return; 
     } 

    // read blocksize to find metadata header 
    metaInt = Convert . ToInt32 (response . GetResponseHeader ("icy-metaint")); 

    try 
     { 
     // open stream on response 
     socketStream = response . GetResponseStream (); 
     byteOut = createNewFile (destPath , fname); 
     // rip stream in an endless loop 
     while (byteOut . Length <1024000) // 23650000 ~ 30 min  
      { 
      // read byteblock 
      int bufLen = socketStream . Read (buffer , 0 , buffer . Length); 
      if (bufLen < 0) 
       return; 

      for (int i=0 ; i < bufLen ; i++) 
       { 
        if (count++ < metaInt) // write bytes to filestream 
         { 
         if (byteOut != null) // as long as we don't have a songtitle, we don't open a new file and don't write any bytes 
          { 
          byteOut . Write (buffer , i , 1); 
          if (count % 100 == 0) 
           byteOut . Flush (); 
          } 
         } 
        else // get headerlength from lengthbyte and multiply by 16 to get correct headerlength 
         { 
         metadataLength = Convert . ToInt32 (buffer [ i ]) * 16; 
         count = 0; 
         } 
        } 
       } 
      } 

    catch (Exception ex) 
     { 
     Console . WriteLine (ex . Message); 
     } 
    finally 
     { 
     if (byteOut != null) 
      byteOut . Close (); 
     if (socketStream != null) 
      socketStream . Close (); 
     } 
    } 
Смежные вопросы