I
I
Ilya2016-12-05 14:58:09
C++ / C#
Ilya, 2016-12-05 14:58:09

Your client for ShoutCAST. How to send a stream?

Good day!
I am making my own very simple ShoutCast client . I want to make everything that plays in the columns transmitted to the server.
I use NAudio and NAudio.Lame (for encoding). TcpClient for data transfer. I'm pretty bad at this.
But I was able to log in to the server, and create a point, a stream (or whatever they are called correctly). But when transferring the buffer to the server, the server complained about not matching the codec format. Began to encode to mp3 . But it turned out only to save to disk and then transfer to the server, I didn’t understand how to make a Stream of recoded data and send it to the server.
Maybe someone who knows about this can help.

using System;
using System.Text;
using NAudio;
using System.IO;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System.Net.Sockets;
 
 
class Program
    {
        static BufferedWaveProvider waveProvider;
        static ShoutCastHelper netshout;
        static void Main(string[] args)
        {
            //создаем клиент
            netshout = new ShoutCastHelper("10.11.13.215", 4200);
            //пытаемся создать поток
            if (netshout.CreateStream())
            {
                waveProvider = new BufferedWaveProvider(new WaveFormat());
 
                //слушаем колонки по-умолчанию
                var waveIn = new WasapiLoopbackCapture();
                waveIn.DataAvailable += WaveIn_DataAvailable;
                
                //начинаем записывать
                waveIn.StartRecording();
            }
 
            Console.ReadKey();
        }
 
        private static void WaveIn_DataAvailable(object sender, WaveInEventArgs e)
        {
            //пытаемся послать с колонок на сервер
 
            //чтобы это не было
            waveProvider.AddSamples(e.Buffer, 0, e.BytesRecorded);
 
            //делаем котопса из буфера
            byte[] buf = new byte[waveProvider.BufferLength];
            int o = waveProvider.Read(buf, 0, buf.Length);
                       
            //кодер. читаем исходный поток и записываем в файл
            var lam = new NAudio.Lame.LameMP3FileWriter("out.mp3", new WaveFormat(), NAudio.Lame.LAMEPreset.ABR_128);
            lam.Write(buf, 0, buf.Length);
            lam.Close();
 
            //читаем файл. что за велосипед?
            var fileBufMp3 = File.ReadAllBytes("out.mp3");
 
            //шлём на сервер
            netshout.SendSteam(fileBufMp3);
 
            //очистка
            waveProvider.ClearBuffer();
        }
    }
 
    public class ShoutCastHelper
    {
        string answerServer;
        public bool isConnect { get; set; }
 
        NetworkStream stream;
        TcpClient client;
        
 
        public ShoutCastHelper(string server, int port)
        {
            Console.WriteLine("Connection ...");
 
            
            client = new TcpClient(server, port);
 
            //посылаем пароль для авторизации точки #1
            Byte[] data = System.Text.Encoding.ASCII.GetBytes("123\n");
 
            // получем Stream для чтения и записи на сервер
            stream = client.GetStream();
 
            //посылаем пароль
            stream.Write(data, 0, data.Length);
 
            System.Threading.Thread.Sleep(50);  //ждём для подключения
 
            data = new Byte[256]; //генерирум новый буфер для ответа      
 
            Int32 bytes = stream.Read(data, 0, data.Length);
            answerServer = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
 
            //проверяем на авторизацию
            isConnect = answerServer.Contains("OK2");
            if (isConnect)
                Console.WriteLine("Connect! WOW!");
            //мы прошли автризацию. Мы молодцы! Ђ  
 
        }
 
        public bool CreateStream()
        {
            if (!isConnect)
                return false;
 
            try
            {
                //назначаем параметры потока
                string radioArgs = "icy-name:MY RADIO\n" +
                "ice-url:127.0.0.1:4200\n" +
                "ice-genre:BDSM\n" +
                "ice-bitrate:128\n" +
                "ice-private:0\n" +
                "ice-public:1\n" +
                "ice-description:This is My Radio\n" +
                "content-type:audio/mp3\n\n";
 
                var data = System.Text.Encoding.ASCII.GetBytes(radioArgs);
                stream = client.GetStream();
                stream.Write(data, 0, data.Length);
 
                Console.WriteLine("Create Stream!");
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
 
            return true;
        }
 
        public void SendSteam(byte[] buffer)
        {
            var nullData = System.Text.Encoding.ASCII.GetBytes(String.Empty);
            stream.Write(nullData, 0, nullData.Length);
            //послать к чёр ... на сервер
            stream.Write(buffer, 0, buffer.Length);
        }
        
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question