Ваша собственная веб-радиостанция на основе Icecast2 и Ices2

Layk M
Автор темы, Прапорщик
Прапорщик
Аватара
Layk M
Автор темы, Прапорщик
Прапорщик
Сообщения: 170
Зарегистрирован: 4 июня 2013
С нами: 10 лет 9 месяцев

#1 Layk » 6 марта 2015, 16:50

Это руководство описывает установку и настройку сервера потокового вещания при помощи Icecast2. Для передачи аудиоданных серверу используется Ices2. Ices2 - это программа, которая передает аудиоданные с вашего локального диска потоковому серверу для последующей трансляции клиентам. Ices2 может читать сохраненные аудио файлы (в формате Ogg Vorbis) или использовать прямой поток с вашей звуковой карты. В этой заметке мы будем рассматривать случай, когда Ices2 читает файлы в формате .ogg с локального диска.

Предварительные замечания


Как уже говорилось выше, Ices2 может использовать различные источники аудиоданных и передавать их потоковому серверу. В этом руководстве мы сконфигурируем Ices2 для чтения файлов с локального диска (режим плей-листа) и установим Icecast2 и Ices2 на одну и ту же систему.

Ices2 поддерживает только формат Ogg, так что если вы хотите использовать mp3-файлы, вам сначала необходимо сконвертировать их в нужный формат. (В ранних версиях Ices2 поддерживал mp3, но поддержка была убрана из-за патентных ограничений. Ogg Vorbis - абсолютно свободный и независимый от патентов формат).

Я использую Debian Etch (для пользователей Ubuntu процедура установки и настройки выглядит точно так же) и моя машина имеет IP-адрес 192.168.0.100

Установка и настройка Icecast2


Для установки сервера просто выполните

Код: Выделить всё

apt-get install icecast2


Внимание! Конфигурационный файл icecast.xml должен быть в кодировке UTF-8, если в нем присутствует кирилица!

icecast.xml с комментариями

Код: Выделить всё

<icecast>
    <!-- 
Секция настройки лимитов и ограничений -->
    <
limits>
        <!-- 
Максимальное одновременное количество слушателей -->
        <
clients>1000</clients>
        <!-- 
Максимальное количество источников -->
        <
sources>200</sources>
        <!-- 
Количество потоков для обработки клиентских подключений -->
        <
threadpool>500</threadpool>
        <!-- 
Максимальный размер очереди в байтах для одного слушателя.
        
Если абонент "отстает" вследствие загружености сетиподдерживается
        буфер указанного размера
Если пользователь отстает большечем
        указано
соединение разрывается-->
        <
queue-size>524288</queue-size>
        <!-- 
Тайм-аут для абонента -->
        <
client-timeout>30</client-timeout>
        <!-- 
Максимальное время ожидания запросакогда абонент выполнил
        подключение к серверу 
-->
        <
header-timeout>15</header-timeout>
        <!-- 
Тайм-аут для источника потока -->
        <
source-timeout>10</source-timeout>
        <!-- 
Буферизировать ли поток -->
        <
burst-on-connect>1</burst-on-connect>
        <!-- 
Размер буфера (в байтах)  -->
        <
burst-size>65535</burst-size>
    </
limits>

    <!-- 
Секция авторизации -->
    <
authentication>
        <!-- 
Незашифрованный паролькоторый используется для подключения к
        источнику потока
На данный момент имя пользователя должно быть
        только 
"source" -->
        <
source-password>hackme</source-password>
        <!-- 
Используется у мастер-сервера как часть авторизациикогда
        слейв запрашивает список потоков 
-->
        <
relay-password>hackme</relay-password>

        <!-- 
Имя пользователя и парольиспользуемые для всех функций
        администрирования
. -->
        <
admin-user>admin</admin-user>
        <
admin-password>hackme</admin-password>
    </
authentication>

    <!-- 
Задание точки монтирования для использования по умолчанию -->
    <!--
    <
shoutcast-mount>/live.nsv</shoutcast-mount>
    -->

    <!-- 
Расскоментировать для публикации информации о аудио-потоках сервера
    в icecast2 YP 
-->
    <!--
    <
directory>
        <
yp-url-timeout>15</yp-url-timeout>
        <
yp-url>http://dir.xiph.org/cgi-bin/yp-cgi</yp-url>
    
</directory>
     -->

    <!-- 
Имя хостаИспользуется для подключения к серверу -->
    <
hostname>radio.muff.kiev.ua</hostname>

    <!-- 
Возможно использование нескольких блоков <listener> -->
    <
listen-socket>
        <!-- 
TCP-портиспользуемый порт для клиентских подключений -->
        <
port>8000</port>
        <!--
IP-адресдля привязки к конкретной сетевой картыЕсли не
        указывать
то Icecast будет слушать запросы на всех интерфейсах -->
        <
bind-address>195.3.159.250</bind-address>
        <!-- 
Дополнительные точки монтированияиспользуемые для подключения
        DSP
-совместимых клиентов -->
        <!-- <
shoutcast-mount>/stream</shoutcast-mount> -->
    </
listen-socket>
    <!--
    <
listen-socket>
        <
port>8001</port>
    </
listen-socket>
    -->

    <!-- 
Секция настройки relay -->
    <!--<
master-server>127.0.0.1</master-server>-->
    <!--<
master-server-port>8001</master-server-port>-->
    <!--<
master-update-interval>120</master-update-interval>-->
    <!--<
master-password>hackme</master-password>-->
    <!--<
relays-on-demand>1</relays-on-demand>-->

    <
relay>
        <!-- 
Серверс которого забираем поток -->
        <
server>stream.16bit.fm</server>
        <!-- 
Номер портас которого забираем поток -->
        <
port>9500</port>
        <!-- 
Точка монтирования на удаленном сервере -->
        <
mount>/</mount>
        <!-- 
Локальная точка монтирования -->
        <
local-mount>/16bit.fm</local-mount>
        <!-- 
Забирать поток только по запросутоесть только когда есть
        слушатели этого потока 
-->
        <
on-demand>1</on-demand>
        <!-- 
Ретрансляция метаданных (названия песенгруппetc) -->
        <
relay-shoutcast-metadata>1</relay-shoutcast-metadata>
    </
relay>

    <!-- 
Специфические настройки секции <mount>. Эта секция имеет настройки,
    
которые касаются только конкретной точки монтирования и распостраняется
    на входящий поток
будь это релей либо же клиент источникаИспользуется
    для изменения глобальных
/по умолчанию настроеккоторые приняты с
    потоком
.
    
Нету необходимости указывать для каждого источникахотя можно и
    задавать некоторые определенные параметры
такие как максимальное
    количество слушателей
точка монтированияимя пользователя и пароль,
    
etc.  -->
    <!--
    <
mount>
        <
mount-name>/example-complex.ogg</mount-name>

        <
username>othersource</username>
        <
password>hackmemore</password>

        <
max-listeners>1</max-listeners>
        <
dump-file>/tmp/dump-example1.ogg</dump-file>
        <
burst-size>65536</burst-size>
        <
fallback-mount>/example2.ogg</fallback-mount>
        <
fallback-override>1</fallback-override>
        <
fallback-when-full>1</fallback-when-full>
        <
intro>/example_intro.ogg</intro>
        <
hidden>1</hidden>
        <
no-yp>1</no-yp>
        <
authentication type="htpasswd">
                <
option name="filename" value="myauth"/>
                <
option name="allow_duplicate_users" value="0"/>
        </
authentication>
        <
on-connect>/home/icecast/bin/stream-start</on-connect>
        <
on-disconnect>/home/icecast/bin/stream-stop</on-disconnect>
    </
mount>

    <
mount>
        <
mount-name>/auth_example.ogg</mount-name>
        <
authentication type="url">
            <
option name="mount_add"       value="http://myauthserver.net/notify_mount.php"/>
            <
option name="mount_remove"    value="http://myauthserver.net/notify_mount.php"/>
            <
option name="listener_add"    value="http://myauthserver.net/notify_listener.php"/>
            <
option name="listener_remove" value="http://myauthserver.net/notify_listener.php"/>
        </
authentication>
    </
mount>

    -->

    <!-- 
Этот флаг включает файловый сервер icecast2 -->
    <
fileserve>1</fileserve>

    <
paths>
        <!-- 
Родительский каталогесли chroot включен -->
        <
basedir>/usr/local/share/icecast</basedir>

        <!-- 
Путь в каталогиспользуемый для логирования -->
        <
logdir>/var/log/icecast</logdir>
        <!-- 
Родительский каталог для всех статический файловЭтот каталог
        может местить в себе все стандартные типы файлов
Напримересли
        задан как 
/var/share/icecast2и пришел запрос на
        http
://server:port/mp3/stuff.mp3, то используется файл
        
/var/share/icecast2/mp3/stuff.mp3 -->
        <
webroot>/usr/local/share/icecast/web</webroot>
        <!-- 
Путьзадающий каталог для всех запросов администратора -->
        <
adminroot>/usr/local/share/icecast/admin</adminroot>
        <!-- <
pidfile>/usr/local/share/icecast/icecast.pid</pidfile> -->

        <!-- 
Aliasestreat requests for 'source' path as being for 'dest' path
             May be made specific to a port 
or bound address using the "port"
             
and "bind-address" attributes.
          -->
        <!--
        <
alias source="/foo" dest="/bar"/>
          -->
        <!-- 
Aliasescan also be used for simple redirections as well,
             
this example will redirect all requests for http://server:port/ to
             
the status page
          
-->
        <
alias source="/" dest="/status.xsl"/>
    </
paths>

    <!-- 
Секция логгирования -->
    <
logging>
        <!-- 
Лог файл записи доступа -->
        <
accesslog>access.log</accesslog>
        <!-- 
Лог файл записи ошибок -->
        <
errorlog>error.log</errorlog>
        <!-- <
playlistlog>playlist.log</playlistlog> -->
        <!-- 
Уровень логгирования -->
        <
loglevel>3</loglevel> <!-- 4 Debug3 Info2 Warn1 Error -->
         <!-- 
Максимальный размер лог-файла -->
        <
logsize>100000</logsize>
        <!-- 
Архивирование лог-файловПо умолчанию выключеночтобы
        избежать заполнения файловой системы 
-->
        <!-- <
logarchive>1</logarchive> -->
    </
logging>

    <!-- 
Секция безопасности -->
    <
security>
        <
chroot>0</chroot>
        <!-- 
Запуск от другого пользователя -->
        <
changeowner>
            <
user>icecast</user>
            <
group>icecast</group>
        </
changeowner>
    </
security>
</
icecast
Рабочий icecast.xml

Код: Выделить всё

<icecast>
    <limits>
        <clients>1000</clients>
        <sources>30</sources>
        <threadpool>10</threadpool>
        <queue-size>524288</queue-size>
        <client-timeout>30</client-timeout>
        <header-timeout>15</header-timeout>
        <source-timeout>100</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>5</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>hackme</source-password>
        <!-- Relays log in username '
relay' -->
        <relay-password>hackme</relay-password>

        <!-- Admin logs in with the username given below -->
        <admin-user>admin</admin-user>
        <admin-password>password</admin-password>
    </authentication>

    <!-- 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>era-telecom</hostname>

    <!-- You can use these two if you only want a single listener -->
    <port>8000</port>
    <!--<bind-address>127.0.0.1</bind-address>-->

    <!-- You may have multiple <listener> elements -->
    <listen-socket>
    </listen-socket>
    <!--
    <listen-socket>
        <port>8001</port>
    </listen-socket>
    -->

    <!--<master-server>127.0.0.1</master-server>-->
    <!--<master-server-port>8001</master-server-port>-->
    <!--<master-update-interval>120</master-update-interval>-->
    <!--<master-password>hackme</master-password>-->

    <!-- setting this makes all relays on-demand unless overridden, this is
         useful for master relays which do not have <relay> definitions here.
         The default is 0 -->
    <!--<relays-on-demand>1</relays-on-demand>-->



    <relay>
        <server>ware.catv.ext.ru</server>
        <port>8140</port>
        <mount>/nashe128.mp3</mount>
        <local-mount>/nashe128</local-mount>
        <on-demand>0</on-demand>
        <relay-shoutcast-metadata>1</relay-shoutcast-metadata>
    </relay>

    <relay>
        <server>92.48.107.38</server>
        <port>8529</port>
        <mount>/</mount>
        <local-mount>/subfm</local-mount>
        <on-demand>0</on-demand>
        <relay-shoutcast-metadata>1</relay-shoutcast-metadata>
    </relay>

    <relay>
        <server>88.191.78.249</server>
        <port>8078</port>
        <mount>/</mount>
        <local-mount>/jazz</local-mount>
        <on-demand>0</on-demand>
        <relay-shoutcast-metadata>1</relay-shoutcast-metadata>
    </relay>

    <relay>
        <server>rusradio.10gb.ru</server>
        <port>8000</port>
        <mount>/</mount>
        <local-mount>/rusradio-berlin</local-mount>
        <on-demand>0</on-demand>
        <relay-shoutcast-metadata>1</relay-shoutcast-metadata>
    </relay>

    <relay>
         <server>radio.spark-media.ru</server>
         <port>8000</port>
         <mount>/europaplus</mount>
         <local-mount>/europa</local-mount>
         <on-demand>0</on-demand>
         <relay-shoutcast-metadata>1</relay-shoutcast-metadata>
    </relay>

    <relay>
         <server>80.70.231.195</server>
         <port>9045</port>
         <mount>/</mount>
         <local-mount>/dolgoff</local-mount>
         <on-demand>0</on-demand>
         <relay-shoutcast-metadata>1</relay-shoutcast-metadata>
     </relay>

     <relay>
          <server>sunfm.ru</server>
          <port>8000</port>
          <mount>/</mount>
          <local-mount>/sanfm</local-mount>
          <on-demand>0</on-demand>
          <relay-shoutcast-metadata>1</relay-shoutcast-metadata>
     </relay>

     <relay>
          <server>83.222.4.42</server>
          <port>8880</port>
          <mount>/</mount>
          <local-mount>/shanson</local-mount>
          <on-demand>0</on-demand>
          <relay-shoutcast-metadata>1</relay-shoutcast-metadata>
     </relay>

    <relay>
         <server>radio.retro-retro.ru</server>
         <port>8000</port>
         <mount>/</mount>
         <local-mount>/retro</local-mount>
         <on-demand>0</on-demand>
         <relay-shoutcast>1</relay-shoutcast>
    </relay>

    <relay>
         <server>radio.corbina.ru</server>
         <port>8100</port>
         <mount>/</mount>
         <local-mount>/ultra-corbina</local-mount>
         <on-demand>0</on-demand>
         <relay-shoutcast>1</relay-shoutcast>
    </relay>

    <relay>
          <server>16bit.fm</server>
          <port>9500</port>
          <mount>/</mount>
          <local-mount>/16bit</local-mount>
          <on-demand>0</on-demand>
          <relay-shoutcast>1</relay-shoutcast>
    </relay>

    <relay>
          <server>radio.silver.ru</server>
          <port>8000</port>
          <mount>/</mount>
          <local-mount>/silver</local-mount>
          <on-demand>0</on-demand>
          <relay-shoutcast>1</relay-shoutcast>
    </relay>

    <relay>
          <server>85.21.79.5</server>
          <port>9054</port>
          <mount>/</mount>
          <local-mount>/bigbeat</local-mount>
          <on-demand>0</on-demand>
          <relay-shoutcast>1</relay-shoutcast>
    </relay>

    <relay>
          <server>radio.globalz.ru</server>
          <port>8080</port>
          <mount>/nonstop</mount>
          <local-mount>/global</local-mount>
          <on-demand>0</on-demand>
          <relay-shoutcast>1</relay-shoutcast>
    </relay>

    <relay>
        <server>w02-sw01.akadostream.ru</server>
        <port>8108</port>
        <mount>/radiosport128.mp3</mount>
        <local-mount>/sport</local-mount>
        <on-demand>0</on-demand>
        <relay-shoutcast>1</relay-shoutcast>
    </relay>

    <relay>
        <server>radio.echo.msk.ru</server>
        <port>8000</port>
        <mount>/</mount>
        <local-mount>/echo_msk</local-mount>
        <on-demand>0</on-demand>
        <relay-shoutcast>1</relay-shoutcast>
    </relay>

    <relay>
        <server>85.21.79.5</server>
        <port>8071</port>
        <mount>/</mount>
        <local-mount>/ragnarok</local-mount>
        <on-demand>0</on-demand>
        <relay-shoutcast>1</relay-shoutcast>
    </relay>

    <relay>
        <server>mp3.radioultra.ru</server>
        <port>80</port>
        <mount>/nashe-64</mount>
        <local-mount>/nashe-64</local-mount>
        <on-demand>0</on-demand>
        <relay-shoutcast-metadata>1</relay-shoutcast-metadata>
    </relay>

    <relay>
        <server>mp3.radioultra.ru</server>
        <port>80</port>
        <mount>/nashe-128</mount>
        <local-mount>/nashe-128</local-mount>
        <on-demand>0</on-demand>
        <relay-shoutcast-metadata>1</relay-shoutcast-metadata>
    </relay>


    <!-- Only define a <mount> section if you want to use advanced options,
         like alternative usernames or passwords
    <mount>
        <mount-name>/example-complex.ogg</mount-name>

   
        <username>othersource</username>
        <password>hackmemore</password>

        <max-listeners>1</max-listeners>
        <dump-file>/tmp/dump-example1.ogg</dump-file>
        <burst-size>65536</burst-size>
        <fallback-mount>/example2.ogg</fallback-mount>
        <fallback-override>1</fallback-override>
        <fallback-when-full>1</fallback-when-full>
        <intro>/example_intro.ogg</intro>
        <hidden>1</hidden>
        <no-yp>1</no-yp>
        <authentication type="htpasswd">
                <option name="filename" value="myauth"/>
                <option name="allow_duplicate_users" value="0"/>
        </authentication>
        <on-connect>/home/icecast/bin/stream-start</on-connect>
        <on-disconnect>/home/icecast/bin/stream-stop</on-disconnect>
    </mount>

    <mount>
        <mount-name>/auth_example.ogg</mount-name>
        <authentication type="url">
            <option name="mount_add"       value="http://myauthserver.net/notify_mount.php"/>
            <option name="mount_remove"    value="http://myauthserver.net/notify_mount.php"/>
            <option name="listener_add"    value="http://myauthserver.net/notify_listener.php"/>
            <option name="listener_remove" value="http://myauthserver.net/notify_listener.php"/>
        </authentication>
    </mount>

    -->

    <fileserve>1</fileserve>

    <!-- 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>
    -->

    <paths>
      <!-- basedir is only used if chroot is enabled -->
        <basedir>/usr/share/icecast2</basedir>

        <!-- Note that if <chroot> is turned on below, these paths must both
             be relative to the new root, not the original root -->
        <logdir>/var/log/icecast2</logdir>
        <webroot>/usr/share/icecast2/web</webroot>
        <adminroot>/usr/share/icecast2/admin</adminroot>
        <!-- <pidfile>/usr/share/icecast2/icecast.pid</pidfile> -->

        <!-- Aliases: treat requests for '
source' path as being for 'dest' path
             May be made specific to a port or bound address using the "port"
             and "bind-address" attributes.
          -->
        <!--
        <alias source="/foo" dest="/bar"/>
          -->
        <!-- Aliases: can also be used for simple redirections as well,
             this example will redirect all requests for http://server:port/ to
             the status page
          -->
        <alias source="/" dest="/status.xsl"/>
    </paths>

    <logging>
        <accesslog>access.log</accesslog>
        <errorlog>error.log</errorlog>
        <!-- <playlistlog>playlist.log</playlistlog> -->
         <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>nobody</user>
            <group>nogroup</group>
        </changeowner>
        -->
    </security>
</icecast>

Затем отредактируйте файл /etc/icecast2/icecast.xml. Большинство значений по умолчанию вполне работоспособны, но необходимо изменить данные для авторизации в секции <authentication>...</authentication>.
Source-password - это пароль, который использует Ices2 для соединения с Icecast2.
Admin-password - это пароль для администраторского доступа к веб-интерфейсу.
Relay-password мы использовать не будем, но, тем не менее, вы должны его поменять.

Код: Выделить всё

[...]
    <authentication>
        <!-- Sources log in with username 'source' -->
        <source-password>password1</source-password>

        <!-- Relays log in username 'relay' -->
        <relay-password>password2</relay-password>

        <!-- Admin logs in with the username given below -->
        <admin-user>admin</admin-user>

        <admin-password>password3</admin-password>
    </authentication>
 


Затем отредактируйте файл /etc/default/icecast2 и установите параметр ENABLE в значение true.

Код: Выделить всё

# Defaults for icecast2 initscript
# sourced by /etc/init.d/icecast2
# installed at /etc/default/icecast2 by the maintainer scripts

#
# This is a POSIX shell fragment
#

# Full path to the server configuration file
CONFIGFILE="/etc/icecast2/icecast.xml"

# Name or ID of the user and group the daemon should run under
USERID=icecast2
GROUPID
=icecast

# Edit /etc/icecast2/icecast.xml and change at least the passwords.
# Change this to true when done to enable the init.d script
ENABLE=true


Вот и все, можно запускать сервер.

Код: Выделить всё

/etc/init.d/icecast2 start


Теперь вы можете зайти браузером на http://192.168.0.100:8000/ (замените 192.168.0.100 на ваш IP-адрес или FQDN) и увидите веб-интерфейс Icecast2

Изображение

Изображение

Изображение

Установка и настройка Ices2


Для установки Ices2 просто наберите команду

Код: Выделить всё

apt-get install ices2


Теперь создайте директории /var/log/ices (для лог-файлов Ices2), /etc/ices2 (для конфигурационных файлов), и /etc/ices2/music (здесь буду хранить наши .ogg-файлы)

Код: Выделить всё

mkdir /var/log/ices
mkdir 
/etc/ices2
mkdir 
/etc/ices2/music


Ices2 поставляется с тремя примерами конфигурационных файлов:

  • /usr/share/doc/ices2/examples/ices-alsa.xml,
  • /usr/share/doc/ices2/examples/ices-oss.xml и
  • /usr/share/doc/ices2/examples/ices-playlist.xml

Мы будем использовать последний, так как мы будем создавать плейлист из локальных .ogg-файлов, которые мы хотим транслировать слушателям. Поэтому мы копируем этот файл в /etc/ices2:

Код: Выделить всё

cp /usr/share/doc/ices2/examples/ices-playlist.xml /etc/ices2


Теперь редактируем файл /etc/ices2/ices-playlist.xml. Большинство значений по умолчанию подойдут для наших целей, но некоторые необходимо изменить. Поменяйте <background>0</background> на <background>1</background> для запуска Ices2 в фоновом режиме.
Измените значения в секции
<metadata>...</metadata>, пропишите полный путь к плейлистам в секции <input>...</input> и введите реальные пароли для Icecast2 в секции <instance>...</instance>. Также в этой секции вы можете изменить битрейт для аудиопотока.

Код: Выделить всё

<?xml version="1.0"?>
<ices>
    <!-- run in background -->
    <background>1</background>

    <!-- where logs, etc go. -->
    <logpath>/var/log/ices</logpath>
    <logfile>ices.log</logfile>
    <!-- 1=error,2=warn,3=info,4=debug -->
    <loglevel>4</loglevel>

    <!-- set this to 1 to log to the console instead of to the file above -->
    <consolelog>0</consolelog>

    <!-- optional filename to write process id to -->
    <!-- <pidfile>/home/ices/ices.pid</pidfile> -->

    <stream>
        <!-- metadata used for stream listing (not currently used) -->
        <metadata>
            <name>Example stream name</name>
            <genre>Example genre</genre>

            <description>A short description of your stream</description>
        </metadata>

        <!-- input module

            The module used here is the playlist module - it has
            'submodules' for different types of playlist. There are
            two currently implemented, 'basic', which is a simple
            file-based playlist, and 'script' which invokes a command
            to returns a filename to start playing. -->

        <input>
            <module>playlist</module>

            <param name="type">basic</param>
            <param name="file">/etc/ices2/playlist.txt</param>
            <!-- random play -->
            <param name="random">0</param>

            <!-- if the playlist get updated that start at the beginning -->
            <param name="restart-after-reread">0</param>
            <!-- if set to 1 , plays once through, then exits. -->
            <param name="once">0</param>
        </input>

                <!-- Stream instance
            You may have one or more instances here. This allows you to
            send the same input data to one or more servers (or to different
            mountpoints on the same server). Each of them can have different
            parameters. This is primarily useful for a) relaying to multiple
            independent servers, and b) encoding/reencoding to multiple
            bitrates.
            If one instance fails (for example, the associated server goes
            down, etc), the others will continue to function correctly.
            This example defines two instances as two mountpoints on the
            same server.  -->
        <instance>
            <!-- Server details:
                You define hostname and port for the server here, along with
                the source password and mountpoint.  -->
            <hostname>localhost</hostname>
            <port>8000</port>

            <password>password1</password>
            <mount>/example1.ogg</mount>

            <!-- Reconnect parameters:
                When something goes wrong (e.g. the server crashes, or the
                network drops) and ices disconnects from the server, these
                control how often it tries to reconnect, and how many times
                it tries to reconnect. Delay is in seconds.
                If you set reconnectattempts to -1, it will continue
                indefinately. Suggest setting reconnectdelay to a large value
                if you do this.
            -->
            <reconnectdelay>2</reconnectdelay>

            <reconnectattempts>5</reconnectattempts>

            <!-- maxqueuelength:
                This describes how long the internal data queues may be. This
                basically lets you control how much data gets buffered before
                ices decides it can't send to the server fast enough, and
                either shuts down or flushes the queue (dropping the data)
                and continues.
                For advanced users only.
            -->
            <maxqueuelength>80</maxqueuelength>

            <!-- Live encoding/reencoding:
                Currrently, the parameters given here for encoding MUST
                match the input data for channels and sample rate. That
                restriction will be relaxed in the future.
            -->

            <encode>
                <nominal-bitrate>64000</nominal-bitrate> <!-- bps. e.g. 64000 for 64 kbps -->
                <samplerate>44100</samplerate>
                <channels>2</channels>

            </encode>
        </instance>

        </stream>
</ices>


Затем разместите ваши ogg-файлы в директории /etc/ices2/music
Помните, что большинство композиций защищены авторскими правами и вам необходимо произвести лицензионные отчисления правообладателям для трансляции произведения в общий доступ

После этого создайте файл /etc/ices2/playlist.txt и поместите в него полные пути к вашим ogg-файлам:

Код: Выделить всё

[...]
/
etc/ices2/music/1vs0_JuniorGroove.ogg
/etc/ices2/music/1vs0_TheWavechangerSuperhero.ogg
[...] 


Затем запустите Ices2

Код: Выделить всё

ices2 /etc/ices2/ices-playlist.xml


В веб-интерфейсе Ices2 вы должны увидеть ссылку на новый аудиопоток (щелкните Listen -> http://192.168.0.100:8000/example1.ogg.m3u. Ссылка http://192.168.0.100:8000/example1.ogg также должна быть работоспособна).

Изображение

Клиенты могут подключаться к серверу с помощью любого проигрывателя, поддерживающего прием потокового вещания, например, WinAMP:

Изображение

Для остановки сервера наберите:

Код: Выделить всё

kill -`pidof ices2


Добавление стартового скрипта для Ices2
В комплекте ices2 нет сценария, который позволяет выполнять автоматический запуск, остановку и перезагрузку сервера. Поэтому мы приводим здесь исходный код этого скрипта:

Код: Выделить всё

#! /bin/sh
#
# icecast2
#
#                Written by Miquel van Smoorenburg <miquels@cistron.nl>.
#                Modified for Debian
#                by Ian Murdock <imurdock@gnu.ai.mit.edu>.
#
#                Further modified by Keegan Quinn <ice@thebasement.org>
#                for use with Icecast 2
#

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON
=/usr/bin/icecast2
NAME
=icecast2
DESC
=icecast2
ICES
=/usr/bin/ices2
ICES_CONFIGFILE
=/etc/ices2/ices-playlist.xml

test 
-x $DAEMON || exit 0

# Defaults
CONFIGFILE="/etc/icecast2/icecast.xml"
CONFIGDEFAULTFILE="/etc/default/icecast2"
USERID=icecast2
GROUPID
=icecast
ENABLE
="false"

# Reads config file (will override defaults above)
[ -"$CONFIGDEFAULTFILE" ] && . $CONFIGDEFAULTFILE

if 
[ "$ENABLE" != "true" ]; then
        echo 
"$NAME daemon disabled - read $CONFIGDEFAULTFILE."
        exit 0
fi

set 
-e

case 
"$1" in
  start
)
        echo -"Starting $DESC: "
        start-stop-daemon --start --quiet --chuid $USERID:$GROUPID \
                --exec $DAEMON -- --c $CONFIGFILE
        sleep 3
        start
-stop-daemon --start --quiet --exec $ICES $ICES_CONFIGFILE
        echo 
"$NAME."
        ;;
  stop)
        echo -"Stopping $DESC: "
        start-stop-daemon --stop --oknodo --quiet --exec $ICES

        start
-stop-daemon --stop --oknodo --quiet --exec $DAEMON
        echo 
"$NAME."
        ;;
  reload|force-reload)
        echo "Reloading $DESC configuration files."
        start-stop-daemon --stop --oknodo --quiet --exec $ICES
        start
-stop-daemon --stop --signal 1 --quiet --exec $DAEMON
        sleep 3
        start
-stop-daemon --start --quiet --exec $ICES $ICES_CONFIGFILE
        
;;
  restart)
        echo -"Restarting $DESC: "
        start-stop-daemon --stop --oknodo --quiet --exec $ICES

        start
-stop-daemon --stop --oknodo --quiet --exec $DAEMON
        sleep 3
        start
-stop-daemon --start --quiet --chuid $USERID:$GROUPID \
                --exec $DAEMON -- --c $CONFIGFILE
        sleep 3
        start
-stop-daemon --start --quiet --exec $ICES $ICES_CONFIGFILE
        echo 
"$NAME."
        ;;
  *)
        echo "Usage: $0 {start|stop|restart|reload|force-reload}" >&2
        exit 1
        
;;
esac

exit 0


Скопируйте код и вставьте его в файл /etc/init.d/ices2. Теперь Ices2 будет запускаться/останавливаться/перезапускаться одновремено с Icecast2, а также будет стартовать на этапе загрузки системы.
Изображение


  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Радиовещание»

Кто сейчас на форуме (по активности за 5 минут)

Сейчас этот раздел просматривают: 3 гостя