Создание собственной радиостанции в сети Интернет

Решил написать небольшую статью, описывающую процесс создания радиостанции.

Всё, что нам понадобится, это сервер с операционной системой Linux, консольный мультиформатный проигрыватель MPD и вещатель потока Icecast2.

Есть достаточно большое количество консольных проигрывателей, но я остановился именно, на MPD, так, как он может играть большое количество аудио форматов, например Ogg Vorbis, FLAC, OggFLAC, MP2, MP3, MP4/AAC, MOD, Musepack, APE и WAV.

Так, как я решил вещать в формате Ogg Vorbis, то выбор проигрывателя у меня был не так велик, решил ставить MPD, который один из немногих, поддерживает необходимый мне формат.

Что касается именно «вещалок», то подобного программного обеспечения не так много, но это не значит, оно не качественное или малофункциональное.

Я остановился на Icecast2, который является аналогом программы SHOUTcast компании Nullsoft, однако Icecast2 имеет более развитую функциональность и поддерживает большее количество форматов потоков (в том числе и Ogg Vorbis). При передаче данных Icecast2 поддерживает теги в UTF-8, что позволяет организовывать трансляцию с национальной аннотацией (в том числе и русской, разумеется).

В качестве серверной платформы я использую Ubuntu-Server (но вы можете использовать любой, удобный для вас дистрибутив), дальнейшее описание я буду вести на примере Ubuntu-Server.

Итак, для настройки проигрывателя MPD, его надо установить.

sudo apt-get install mpd

После установки, проигрыватель запустится с конфигом по умолчанию (/etc/mpd.conf).

Убиваем проигрыватель sudo killall mpd -9

Перед настройкой проигрывателя, неплохо было бы сохранить его изначальный конфиг, после чего открываем /etc/mpd.conf для редактирования, например, так

sudo nano /etc/mpd.conf

И правим конфиг под свои нужды. Мой конфиг выглядит так:

# директория с музыкой
#
music_directory "/var/wwwroot/@_mpd/music"
# директория для плей листов
#
playlist_directory "/var/wwwroot/@_mpd/playlists"
#
# директория вспомогательных файлов (все, кроме, pid должны быть вручную созданы!)
#
db_file "/var/wwwroot/@_mpd/tag_cache"
#
log_file "/var/wwwroot/@_mpd/mpd.log"
#
pid_file "/var/wwwroot/@_mpd/pid"
#
state_file "/var/wwwroot/@_mpd/state"
#
#
# General music daemon options ################################################
#
# пользователь, от которого запускать плеер
# многие рекомендуют использовать пользователя mpd, но с ним так и не заработал плеер
# я использую своего домашнего пользователя
#
user "username"
#
#bind_to_address "localhost"
#
# And for Unix Socket
#bind_to_address "/var/run/mpd/socket"
#
# порт лучше оставить по-умолчанию
#
port "6600"
#
log_level "default"
#
# If you have a problem with your MP3s ending abruptly it is recommended that
# you set this argument to "no" to attempt to fix the problem. If this solves
# the problem, it is highly recommended to fix the MP3 files with vbrfix
# (available from ), at which
# point gapless MP3 playback can be enabled.
#
gapless_mp3_playback "yes"
#
# This setting enables MPD to create playlists in a format usable by other
# music players.
#
save_absolute_paths_in_playlists "yes"
#
# This setting defines a list of tag types that will be extracted during the
# audio file discovery process. Optionally, 'comment' can be added to this
# list.
# мета данные, которые будут отображаться в проигрывателе пользователя
# у меня, название радиостанции плеер почему-то не показывает :0((
#metadata_to_use "artist,album,title,track,name,genre,date,composer,performer,disc"
#
metadata_to_use "name,artist,title"

# Symbolic link behavior ###################################################### 
# If this setting is set to "yes", MPD will discover audio files by following
# symbolic links outside of the configured music_directory.
#
#follow_outside_symlinks "yes"
#
# If this setting is set to "yes", MPD will discover audio files by following
# symbolic links inside of the configured music_directory.
#
#follow_inside_symlinks "yes" 
#
# Zeroconf / Avahi Service Discovery ##########################################
#
# If this setting is set to "yes", service information will be published with
# Zeroconf / Avahi.
#
zeroconf_enabled "yes"
#
# The argument to this setting will be the Zeroconf / Avahi unique name for
# this MPD server on the network.
#
zeroconf_name "Music Player"
#
# Permissions #################################################################
#
# If this setting is set, MPD will require password authorization. The password
# can setting can be specified multiple times for different password profiles.
#
# авторизация плеера (так и не понял зачем нужен пароль на запуск)
#
#password "pass@read,add,control,admin"
#
# This setting specifies the permissions a user has who has not yet logged in.
#
default_permissions "read,add,control,admin"

# Input ####################################################################### #
# вот честное слово, фиг знает зачем это
#
#input {
# plugin "curl"
# proxy "proxy.isp.com:8080"
# proxy_user "user"
# proxy_password "password"
#}
#
# Audio Output ################################################################
#
# ЗДЕСЬ НАСТРАИВАЮТСЯ РАЗЛИЧНЫЕ ЗВУКОВЫЕ СИСТЕМЫ ДЛЯ
# РАБОТЫ СЕРВЕРА. Если вы собираетесь только играть радио, за комментируйте всё
#
# MPD supports various audio output types, as well as playing through multiple
# audio outputs at the same time, through multiple audio_output settings
# blocks. Setting this block is optional, though the server will only attempt
# autodetection for one sound card.
#
# See for examples of
# other audio outputs.
#
# An example of an ALSA output:
#
#audio_output {
# type "alsa"
# name "SI7012"
# device "hw:0,0" # optional
# format "44100:16:2" # optional
# mixer_device "default" # optional
# mixer_control "Master" # optional
# mixer_index "0" # optional
#}
#
# An example of an OSS output:
#
#audio_output {
# type "oss"
# name "My OSS Device"
# device "/dev/dsp" # optional
# format "44100:16:2" # optional
# mixer_device "/dev/mixer" # optional
# mixer_control "PCM" # optional
#}
#
# An example of a shout output (for streaming to Icecast):
#
# ВСЁ, КРОМЕ ЭТОГО РАЗДЕЛА, ОТВЕЧАЮЩЕГО ЗА ТРАНСЛЯЦИЮ
#
audio_output {
type "shout"
#
# в каком формате будет осуществляться вещание
#
encoding "ogg" # optional
name "Anime cyber radio acrobs.net"
host "localhost"
port "8000"
#
# точка монтирования — выбирайте название, которое понравится
# но эта же точка монтирования должна быть позже прописана
# в настройках Icecast2
#
mount "/acrobs.ogg"
#
# пароль на доступ вещалки к плееру, название подобно описанию выше
#
password "mypass"
#
# выбор качества звучания используется директива либо quality либо bitrate
# одновременно не работают! Лучше явно указывать bitrate
#
# quality "8.0"
bitrate "256"
#
# формат звукового потока частота: количество бит: количество каналов
# 2 — стерео :0))
#
format "44100:16:2"
protocol "icecast2" # optional
# user "source" # optional
#
# описание и жанр станции
#
description "Original Sound Tracks From Anime & Japan Music"
genre "Anime OST's" # optional
public "yes" # optional
# timeout "2" # optional
}
#
# An example of a httpd output (built-in HTTP streaming server):
#
#audio_output {
# type "httpd"
# name "My HTTP Stream"
# encoder "vorbis" # optional, vorbis or lame
# port "8000"
# quality "5.0" # do not define if bitrate is defined
# bitrate "128" # do not define if quality is defined
# format "44100:16:1"
#}
#
# An example of a pulseaudio output (streaming to a remote pulseaudio server)
#
#audio_output {
# type "pulse"
# name "My Pulse Output"
# server "remote_server" # optional
# sink "remote_server_sink" # optional
#}
#
## Example "pipe" output:
#
#audio_output {
# type "pipe"
# name "my pipe"
# command "aplay -f cd 2>/dev/null"
## Or if you're want to use AudioCompress
# command "AudioCompress -m | aplay -f cd 2>/dev/null"
## Or to send raw PCM stream through PCM:
# command "nc example.org 8765"
# format "44100:16:2"
#}
#
## An example of a null output (for no audio output):
#
#audio_output {
# type "null"
# name "My Null Output"
#}
#
# This setting will change all decoded audio to be converted to the specified
# format before being passed to the audio outputs. By default, this setting is
# disabled.
#
# снова формат выходного звука. Не знаю зачем дублируются
# у меня записи одинаковы
#
audio_output_format "44100:16:2"
#
# If MPD has been compiled with libsamplerate support, this setting specifies
# the sample rate converter to use. Possible values can be found in the
# mpd.conf man page or the libsamplerate documentation. By default, this is
# setting is disabled.
#
# типы конвертации, можно поискать значения, у меня всё по-дефолту
#samplerate_converter "Fastest Sinc Interpolator"
#
#
# Volume control mixer ########################################################
#
# These are the global volume control settings. By default, this setting will
# be detected to the available audio output device, with preference going to
# hardware mixing. Hardware and software mixers for individual audio_output
# sections cannot yet be mixed.
#
# An example for controlling an ALSA, OSS or Pulseaudio mixer; If this
# setting is used other sound applications will be affected by the volume
# being controlled by MPD.
#
#mixer_type "hardware"
#
# An example for controlling all mixers through software. This will control
# all controls, even if the mixer is not supported by the device and will not
# affect any other sound producing applicaпо-дефолту
#
# тип регулятора громкости потока
#
mixer_type "software"
#
# This example will not allow MPD to touch the mixer at all and will disable
# all volume controls.
#
#mixer_type "disabled"
#
###############################################################################

# Normalization automatic volume adjustments ##################################
#
# This setting specifies the type of ReplayGain to use. This setting can have
# the argument "album" or "track". See for more
# details. This setting is disabled by default.
#
# выравнивание громкости
#
replaygain "album"
#
# This setting sets the pre-amp used for files that have ReplayGain tags. By
# default this setting is disabled.
#
#replaygain_preamp "0"
#
# This setting enables on-the-fly normalization volume adjustment. This will
# result in the volume of all playing audio to be adjusted so the output has
# equal "loudness". This setting is disabled by defгромкости
#
# нормализация громкости «на лету»
#
volume_normalization "yes"
#
###############################################################################

# MPD Internal Buffering ######################################################
#
# This setting adjusts the size of internal decoded audio buffering. Changing
# this may have undesired effects. Don't change this if you don't know what you
# are doing.
#
# размер аудио буфера
#
audio_buffer_size "2048"
#
# This setting controls the percentage of the buffer which is filled before
# beginning to play. Increasing this reduces the chance of audio file skipping,
# at the cost of increased time prior to audio playback.
#
# буферизация до начала воспроизведения
#
buffer_before_play "10%"
#
#
# Resource Limitations ########################################################
#
# These settings are various limitations to prevent MPD from using too many
# resources. Generally, these settings should be minimized to prevent security
# risks, depending on the operating resources.
#
# тайм-аут соединения
#
connection_timeout "60"
#
# максимальное количество соединений «вещалок» НЕ СЛУШАТЕЛЕЙ!!!
#
max_connections "5"
#max_playlist_length "16384"
#max_command_list_size "2048"
#max_output_buffer_size "8192"
#
#
#
# Character Encoding ##########################################################
#
# If file or directory names do not display correctly for your locale then you
# may need to modify this setting. After modification of this setting mpd
# --create-db must be run to change the database.
#
# кодировки без комментариев
#
filesystem_charset "UTF-8"
#
# This setting controls the encoding that ID3v1 tags should be converted from.
#
id3v1_encoding "UTF-8"
#

После того, как файл настроек приведён в «правильный» вид, необходимо создать директории и файлы, которые были описаны в первых строках файла настроек.

Сейчас нам надо немного отвлечься от самого музыкального демона и поставить клиента — программу управления демоном MPD.

Для этого, ставим MPC — консольный клиент управления MPD.

sudo apt-get install mpc

Далее заливаем музыку в соответствующую директорию и ОБЯЗАТЕЛЬНО создаём список воспроизведения это придётся делать каждый раз при добавлении музыки:

mpd —create-db
mpc ls |mpc add

После этого MPD запустится сам. В случае ошибок конфигов, надо будет их исправить. Повторный запуск проигрывателя производится из под своего пользователя БЕЗ sudo!

/etc/init.d/mpd start

Для старта проигрывателя, выполняем в консоли команду:

mpc play

После чего, можно будет узнать работает или нет проигрыватель, посмотрев результат работы предыдущей команды, которая должна вывести что-то типа:

Rungran - The Reaper
[playing] #81/155 0:08/2:58 (4%)
volume:100% repeat: on random: on single: off consume: off

Команда

man mpc

Подскажет, что ещё может делать MPC.

При перезагрузке сервера, MPD будет сам стартовать автоматически, чего нельзя сказать о начале проигрывания плеером трека.

Исправляем ситуацию, добавив скрипт в автозагрузку с примерным содержанием:

#!/bin/sh
sleep 10;
mpc play;

Десятисекундная задержка нужна для того, чтобы музыкальный проигрыватель успел загрузиться до того, как мы дадим ему команду на воспроизведения трека.

Если всё заработало, то можно приступать к установке и настройке «вещалки» Icecast2.

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

apt-get install icecast2

Было бы не плохо, предварительно сделать резервную копию файла настроек /etc/icecast2/icecast.xml.

Затем отредактируйте файл /etc/icecast2/icecast.xml. Большинство значений по умолчанию вполне работоспособны, но необходимо изменить данные для авторизации в секции

Затем отредактируйте файл /etc/icecast2/icecast.xml. Большинство значений по умолчанию вполне работоспособны, но необходимо изменить данные для авторизации в секции
=authentication==/authentication=

Мой файл настроек /etc/icecast2/icecast.xml выглядит так

После установки Icecast2, его запуск запрещён в системе.

Для исправления ситуации, правим конфиг /etc/default/icecast2

# 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

Заменив в последней строчке false на true.
Для остановки/запуска/перезапуска, используем скрипт с правами суперпользователя
/etc/init.d/icecast2 start|stop|restart

Для возможности управления своей интернет радиостанцией через web интерфейс, можете установить Pitchfork Music Player Daemon Client.

В комментариях к настройке Icecast2, я писал, что посмотреть работу сервера можно набрав в адресной строке браузера адрес вашего сервера и номер порта, указанного в настройках.

Для моего случая, это
192.168.0.100:8000/

* This source code was highlighted with Source Code Highlighter.

Вы увидите информацию о работе Icecast2 и ссылку на воспроизведение музыки.

Можно попробовать кликнуть эту ссылку и проверить, вещает ли радио.

Надо отметить, что Icecast2 может ретранслировать чужие радиостанции (в конфиг Icecast2 я добавил закомментированный пример ретрансляции сторонней радиостанции).

После того, как мы убедились, что поток идёт, можно сделать свой сайт для своего радио и разместить на нём ссылку на список воспроизведения.

Вот, в общем-то и всё.

Если найдёте какие-либо недочёты в статье, я с удовольствием постараюсь сделать её лучше.

  • Hits: 5310

Продвижение сайтов. Создание сайтовРаскрутка в Интернете. Поисковое продвижение. Раскрутка сайтов. Создать сайт. Разработка сайта. Оптимизация сайтов. СЕО продвижение.