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

Это руководство описывает установку и настройку сервера потокового вещания при помощи
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

Затем отредактируйте файл /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

1.png

2.png

3.png

Установка и настройка 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 и Мы будем использовать последний, так как мы будем создавать плейлист из
локальных .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 также должна быть
работоспособна).

44.png

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

4.png

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

kill -9 `pidof ices2`

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

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

#! /bin/sh
#
# icecast2
#
#                Written by Miquel van Smoorenburg .
#                Modified for Debian
#                by Ian Murdock .
#
#                Further modified by Keegan Quinn 
#                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)
[ -r “$CONFIGDEFAULTFILE” ] && . $CONFIGDEFAULTFILE  

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

set -e  

case “$1″ in
  start)
        echo -n “Starting $DESC: ”
        start-stop-daemon –start –quiet –chuid $USERID:$GROUPID \
                –exec $DAEMON — -b -c $CONFIGFILE
        sleep 3
        start-stop-daemon –start –quiet –exec $ICES $ICES_CONFIGFILE
        echo “$NAME.”
        ;;
  stop)
        echo -n “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 -n “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 — -b -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, а также
будет стартовать на этапе загрузки системы.


Оригинал: http://howtoforge.org/linux_webradio_with_icecast2_ices2
Мой перевод на сайте rus-linux.net: http://rus-linux.net/lib.php?name=MyLDP/server/ice.html

Система Orphus

 


 

Comments: 1

  1. Piligrim May 4th, 2009 at 11:44 am

    А не пробывали сделать mpd+icecast+туева туча клиентов, хоть под консоль, хоть под десктом, хоть под веб, даже расширение для фаерфокса

Add a Comment