Go to content Go to menu

Было скучно и нечем было заняться. Решил потрогать сервер потокового аудио. Выбор пал на связку ices + Icecast на базе ОС Centos 5.3 i386. Потыкавшись по репозиториям, так и не нашел подходящих пакетов и решил собрать из исходников.
Здесь я поделюсь опытом:

Для начала установим все необходимые пакеты:
# yum install rpm-devel rpm-libs rpm-build libvorbis-devel libogg-devel
# yum install curl-devel libxslt-devel libtheora-devel speex-devel

Скачаем исходник icecast и установим его (будем считать что компилятор у вас установлен уже):
# wget http://downloads.xiph.org/releases/icecast/icecast-2.3.2.tar.gz
# tar -xvf icecast-2.3.2.tar.gz
# cd icecast-2.3.2
# ./configure
# make
# make install

Для безопасности создадим для него пользователя и группу:
# groupadd icecast
# useradd -g icecast -d /home/icecast -s /sbin/nologin icecast

Создаем каталоги для файлов icecast:
# mkdir /home/icecast/admin 
# mkdir /home/icecast/logs
# chown icecast:icecast /home/icecast/logs
# mkdir /home/icecast/web

Копируем содержимое соответствующих каталогов из /usr/local/share/icecast в наши только что созданные.
Далее копируем пример конфига:
# cp /usr/local/share/icecast/doc/icecast.xml.dist /etc/icecast.xml

                
Делаем владельцем root и ограниченные права для остальных на него, так как этот файл содержит пароли:
# chmod 640 /etc/icecast.xml
# chown root:root /etc/icecast.xml

Ну и вносим соответствующие изменения:

<icecast>
    <limits>
        <clients>100</clients>
        <sources>2</sources>
        <threadpool>5</threadpool>
        <queue-size>524288</queue-size>
        <client-timeout>30</client-timeout>
        <header-timeout>15</header-timeout>
        <source-timeout>10</source-timeout>
        <!-- If enabled, this will provide a burst of data when a client
             first connects, thereby significantly reducing the startup
             time for listeners that do substantial buffering. However,
             it also significantly increases latency between the source
             client and listening client.  For low-latency setups, you
             might want to disable this. -->
        <burst-on-connect>1</burst-on-connect>
        <!-- same as burst-on-connect, but this allows for being more
             specific on how much to burst. Most people won't need to
             change from the default 64k. Applies to all mountpoints  -->
        <burst-size>65535</burst-size>
    </limits>

    <authentication>
        <!-- Sources log in with username 'source' -->
        <source-password>Тут вписываем пароль</source-password>
        <!-- Relays log in username 'relay' -->
        <relay-password>Тут вписываем пароль</relay-password>

        <!-- Admin logs in with the username given below -->
        <admin-user>Имя пользователя с правами к админке</admin-user>
        <admin-password>Пароль админа</admin-password>
    </authentication>
    <!-- set the mountpoint for a shoutcast source to use, the default if not
         specified is /stream but you can change it here if an alternative is
         wanted or an extension is required
    <shoutcast-mount>/live.nsv</shoutcast-mount>
    -->

    <!-- Uncomment this if you want directory listings -->
    <!--
    <directory>
        <yp-url-timeout>15</yp-url-timeout>
        <yp-url>http://dir.xiph.org/cgi-bin/yp-cgi</yp-url>
    </directory>
     -->

    <!-- This is the hostname other people will use to connect to your server.
    It affects mainly the urls generated by Icecast for playlists and yp
    listings. -->
   <hostname>localhost</hostname>

    <!-- You may have multiple <listener> elements -->
    <listen-socket>
        <port>8000</port>
        <!-- <bind-address>127.0.0.1</bind-address> -->
        <!-- <shoutcast-mount>/stream</shoutcast-mount> -->
    </listen-socket>
    <fileserve>1</fileserve>

    <paths>
                <!-- basedir is only used if chroot is enabled -->
        <basedir>/home/icecast</basedir>

        <!-- Note that if <chroot> is turned on below, these paths must both
             be relative to the new root, not the original root -->
        <logdir>/home/icecast/logs</logdir>
        <webroot>/home/icecast/web</webroot>
        <adminroot>/home/icecast/admin</adminroot>
        <pidfile>/home/icecast/icecast.pid</pidfile>
        <alias source="/" dest="/status.xsl"/>
    </paths>

    <logging>
        <accesslog>access.log</accesslog>
        <errorlog>error.log</errorlog>
        <loglevel>4</loglevel> <!-- 4 Debug, 3 Info, 2 Warn, 1 Error -->
        <logsize>10000</logsize> <!-- Max size of a logfile -->
        <!-- If logarchive is enabled (1), then when logsize is reached
             the logfile will be moved to [error|access|playlist].log.DATESTAMP,
             otherwise it will be moved to [error|access|playlist].log.old.
             Default is non-archive mode (i.e. overwrite)
        -->
        <!-- <logarchive>1</logarchive> -->
    </logging>
    <security>
        <chroot>0</chroot>

// ниже строки надо раскоментить и указать нашего польщователя

        <changeowner>
            <user>icecast</user>
            <group>icecast</group>
        </changeowner>
    </security>
</icecast>

Ну собственно, запускаем наш сервер коммандой:
# icecast -b -c /etc/icecast.xml

Не забываем открыть соответствующий порт в фаерволле (см. конфиг). Ну и проверяем, что он стартанул:
# netstat -pan | grep icecast
    tcp        0      0   :::8000                      :::*                       LISTEN      28826/icecast

Также попробуем зайти на веб-интерфейс по адресу:
http://ваш_ip:8000/

 Теперь пришло время собрать ices, который будет конвертить аудио и посылать его на наш сервер icecast. Скачаем и установим необходимые сопутствующие пакеты:
# wget http://siava.ru/forum/go/url.php?url=http://downloads.us.xiph.org/releases/libshout /libshout-2.2.2.tar.gz
# wget http://siava.ru/forum/go/url.php?url=http://surfnet.dl.sourceforge.net/sourceforge/lame/lame-3.97.tar.gz
# tar xvf lame-3.97.tar.gz
# tar xvf libshout-2.2.2.tar.gz
# cd lame-3.97
# ./configure --prefix=/usr
# make && make install
# cd ../libshout-2.2.2
# ./configure --with-ogg --with-vorbis --with-lame --prefix=/usr
# make && make install
# yum install libogg

Скачиваем и собираем сам ices (я предпочел версию 0.4, т.к. в ней еще осталась поддержка формата mp3):

# wget http://downloads.us.xiph.org/releases/ices/ices-0.4.tar.gz
# tar xvf ices-0.4.tar.gz
# cd ices-0.4
# ./configure --with-lame
# make
# make install

Подгоняем конфиг под свои нужды:
nano /etc/ices.conf

<?xml version="1.0"?>
<ices:Configuration xmlns:ices="http://www.icecast.org/projects/ices">
  <Playlist>
    <!-- This is the filename used as a playlist when using the builtin
         playlist handler. -->
    <File>/media/music/playlist.txt</File>
// Тут фигурирует путь до файла с плейлистом (список mp3 файлов для воспроизведения)
    <!-- Set this to 0 if you don't want to randomize your playlist, and to
         1 if you do. -->
    <Randomize>1</Randomize>
    <!-- One of builtin, perl, or python. -->
    <Type>builtin</Type>
    <!-- Module name to pass to the playlist handler if using  perl or python.
         If you use the builtin playlist handler then this is ignored -->
    <Module>ices</Module>
    <!-- Set this to the number of seconds to crossfade between tracks.
         Leave out or set to zero to disable crossfading (the default).
    <Crossfade>5</Crossfade>
    -->
  </Playlist>

  <Execution>
    <!-- Set this to 1 if you want ices to launch in the background as a
         daemon -->
    <Background>1</Background>
    <!-- Set this to 1 if you want to see more verbose output from ices -->
    <Verbose>0</Verbose>
    <!-- This directory specifies where ices should put the logfile, cue file
         and pid file (if daemonizing). Don't use /tmp if you have l33t h4x0rz
         on your server. -->
    <BaseDirectory>/tmp</BaseDirectory>
  </Execution>

  <Stream>
    <Server>
      <!-- Hostname or ip of the icecast server you want to connect to -->
      <Hostname>localhost</Hostname>
      <!-- Port of the same -->
      <Port>8000</Port>
      <!-- Encoder password on the icecast server -->
      <Password>Здесь указываем такой же пароль как и в icecast в разделе sources</Password>
      <!-- Header protocol to use when communicating with the server.
           Shoutcast servers need "icy", icecast 1.x needs "xaudiocast", and
           icecast 2.x needs "http". -->
      <Protocol>http</Protocol>
    </Server>

    <!-- The name of the mountpoint on the icecast server -->
    <Mountpoint>/test</Mountpoint>
// Это наименование потока на сервере icecast
    <!-- The name of the dumpfile on the server for your stream. DO NOT set
         this unless you know what you're doing.
    <Dumpfile>ices.dump</Dumpfile>
    -->
    <!-- The name of you stream, not the name of the song! -->
    <Name>Default stream</Name>
    <!-- Genre of your stream, be it rock or pop or whatever -->
    <Genre>Default genre</Genre>
    <!-- Longer description of your stream -->
    <Description>Default description</Description>
    <!-- URL to a page describing your stream -->
    <URL>http://localhost:8000/test</URL>
    <!-- 0 if you don't want the icecast server to publish your stream on
         the yp server, 1 if you do -->
    <Public>0</Public>

    <!-- Stream bitrate, used to specify bitrate if reencoding, otherwise
         just used for display on YP and on the server. Try to keep it
         accurate -->
    <Bitrate>128</Bitrate>
    <!-- If this is set to 1, and ices is compiled with liblame support,
         ices will reencode the stream on the fly to the stream bitrate. -->
    <Reencode>1</Reencode>
    <!-- Number of channels to reencode to, 1 for mono or 2 for stereo -->
    <!-- Sampe rate to reencode to in Hz. Leave out for LAME's best choice
    <Samplerate>44100</Samplerate>
    -->
    <Channels>2</Channels>
  </Stream>
</ices:Configuration>

Создаем каталог для музыки:
mkdir /media/music
Заливаем туда mp3, которые есть желание транслировать, и создаем плейлист:
# ls /media/music/*.mp3 > /media/music/playlist.txt

Запускаем это добро командой ices -c /etc/ices.conf и проверяем что он подключился к нашему серверу icecast:
# netstat -pan | grep ices
    tcp    0   0   127.0.0.1:46228    127.0.0.1:8000     ESTABLISHED 2796/ices

Пробуем воспроивести наш поток на каком либо плеере, зацепившись на канал по URL: http://ваш_ip:8000/test
test - имя потока (см. конфиг ices.conf)
Должно быть все ок.

Заморачиваться с плеером я не стал, скачал и залил в каталог с сайтом понравившийся мне флешплеер, коих куча в просторах глобальной сети. И добавил в код соответвующий скрипт, выводящий его в нужном месте с указанием зацепиться за только что созданный нами аудиоканал.

5 Ответа(ов) на "Потоковое аудио на сайте."

  1. Nikolay Says:

    О. Как раз искал информацию по настройке своего радио. Выглядит несложным, сейчас попробую. Спасибо

  2. Дмитрий Says:

    Спасибо! Самый вразумительный мануал, что нашел!

  3. Александр Says:

    Спасибо) Рад, что оказалось полезным

  4. jeff Says:

    Спасибо – самое вразумительное, что можно было найти))
    но есть некоторые недочеты
    — нет ices.conf в etc (нужно из /ices-0.4/conf скопировать ices.conf.dist в etc и переименовать его в ices.conf)
    — нужно после wget http://downloads.us.xiph.org/releases/ices/ices-0.4.tar.gz сделать #tar xvf ices-0.4.tar.gz
    а затем уже #cd ices-0.4
    — после запуска icecast -b -c /etc/icecast.xml будет ссылатся на файлы которых нет в /admin, а также /web,,(здесь делаем тоже самое,что и с ices.conf),
    после всего перечисленного -впринципе работает ! ОТЛИЧНЫЙ ХЭЛП – можно сказать из коробочки заработал!
    где только не искал -везде перепечатка с ошибками в настройках – у вас все гуд! спасибо ещё раз !

  5. Александр Says:

    И вам спасибо за замечания. Как доберусь до компа, обязательно поправлю. КОгда пишешь вдохновленно, мысли скачут вперед и забываешь иногда на чем остановился. =)

Leave A Reply

Помощь по Textile