Music Player Daemon (Русский)
MPD (music player daemon) - это музыкальный проигрыватель, имеющий клиент-серверную архитектуру. MPD управляет плейлистами и медиатекой, используя очень мало ресурсов. Для взаимодействия с ним вам нужен отдельный клиент.
Contents
Установка
Последняя стабильная версия mpd доступна в официальном репозитории.
Если вы хотите установить тестовую версию, AUR предлагает вам несколько вариантов, например mpd-gitAUR
Настройка MPD
MPD можно запускать локально (используя конфигурацию пользователя), глобально (настройки применяются для всех пользователей), а также в нескольких экземплярах. Способ запуска (и настройки) зависит от того, как вы хотите использовать MPD (например, для использования на домашней системе более полезен запуск локально).
Чтобы MPD мог воспроизводить аудио, необходимо настроить вывод звука через ALSA или OSS (возможно использование PulseAudio).
Настройка MPD осуществляется редактированием mpd.conf
. Расположение этого файла зависит от того, каким образом вы запускали MPD. Далее перечислены наиболее используемые параметры:
-
pid_file
- Файл, в котором MPD хранит свой pid -
db_file
- База данных медиатеки -
state_file
- Хранит текущее состояние MPD -
playlist_directory
- Директория, в которую сохраняются плейлисты -
music_directory
- Директория, сканируемая MPD, при поиске музыки -
sticker_file
- Файл с метаданными аудиотреков (sticker database)
Глобальные настройки
По умолчанию /etc/mpd.conf
использует /var/lib/mpd
и запускается от пользователя mpd. Но, т.к. /var/lib/mpd
по умолчанию принадлежит пользователю root, вы должны изменить владельца папки, иначе mpd не сможет писать в нее:
# chown -R mpd /var/lib/mpd
Измените /etc/mpd.conf
и добавьте в строку music_directory
путь к вашей папке с музыкой:
music_directory /путь/к/музыке
Директория с музыкой
MPD должен иметь разрешение на выполнение (+x
) для всех директорий музыкальной коллекции, а также доступ на чтение во все директории, содержащие музыкальные файлы. Как правило, это противоречит со стандартной конфигурацией, в которой пользователи хранят свою музыку в своём домашнем каталоге.
Для решения данной проблемы существует несколько способов, которые могут помочь:
- запуск MPD от имени текущего пользователя
- добавить пользователя mpd в текущую пользовательскую группу и предоставить разрешения группе к вашему пользовательскому каталогу:
# gpasswd -a mpd <ваша пользовательская группа> $ chmod 710 /home/<ваш пользовательский каталог>
- поместить свою музыкальную коллекцию в другой каталог путём
а) полного её перемещения в каталог, доступный mpd;
б) монтированием папки с привязкой к каталогу, в который у mpd есть доступ, например:
# mkdir /var/lib/mpd/music # echo "/путь/к/пользовательской/музыке /var/lib/mpd/music none bind" >> /etc/fstab # mount -a
в) в случае с фс Btrfs — подразделом Btrfs (необходимо сделать данные изменения постоянными, путём редактирования файла /etc/fstab
);
г) созданием символической ссылки на папку с музыкой в /var/lib/mpd/music
:
# mkdir /var/lib/mpd/music # ln -s /путь/к/пользовательской/музыке /var/lib/mpd/music/
В конфигурационном файле mpd может быть указана только одна директория с музыкой. Если музыкальная коллекция содержится в различных директориях, создайте символические ссылки в главную директорию (/var/lib/mpd
). Не забудьте установить правильные права на эти директории.
Запуск MPD
MPD можно контролировать через mpd.service
используя systemd. Первый запуск может занять некоторое время, пока MPD будет сканировать вашу папку с музыкой.
Проверьте все, запустив клиентское приложение (ncmpc легкий и простой в использовании клиент) и проиграв какие-нибудь треки.
Сокет активация
Если mpd.socket
включен в то время как mpd.service
(предоставляемый mpd) выключен, systemd не станет запускать mpd, но он будет слушать обращения к сокету. Когда mpd клиент попытается обратиться к сокету, systemd запустит mpd.service
и передаст управление соответствующим портом процессу mpd.
If you prefer to listen on different UNIX sockets or network ports (even multiple sockets of each type), or if you prefer not to listen on network ports at all, you should add/edit/remove the appropriate "ListenStream="
lines in the [Socket]
section of mpd.socket
and modify the appropriate lines /etc/mpd.conf
(see mpd.conf(5) for details).
If you use different (even multiple) network or local sockets, or prefer not to use network sockets at all, simply add, change, or remove lines beginning with "ListenStream="
in the [Socket]
section.
/etc/systemd/system/mpd.socket
[Unit] Description=Music Player Daemon Sockets [Socket] ListenStream=/var/run/mpd/socket ListenStream=6600 [Install] WantedBy=sockets.target
Configure audio
To change the volume for mpd independent from other programs, uncomment or add this switch in mpd.conf:
/etc/mpd.conf
mixer_type "software"
Users of ALSA will want to have the following device definition, which allows software volume control in the MPD client to control the volume separately from other applications.
/etc/mpd.conf
audio_output { type "alsa" name "My Sound Card" mixer_type "software" # optional }
Users of PulseAudio will need to make the following modification:
/etc/mpd.conf
audio_output { type "pulse" name "pulse audio" }
PulseAudio supports multiple advanced operations, e.g. transferring the audio to a different machine. For advanced configuration with MPD see Music Player Daemon Community Wiki.
Changing user
Changing the group that MPD runs as may result in errors like output: Failed to open "My ALSA Device"
, [alsa]: Failed to open ALSA device "default": No such file or directory
or player_thread: problems opening audio device while playing "Song Name.mp3"
.
This is because the MPD users need to be part of the audio group to access sound devices under /dev/snd/
. To fix it add user make the MPD user part of the audio group:
# gpasswd -a mpd audio
Timeline of MPD startup
To depict when MPD drops its superuser privileges and assumes those of the user set in the configuration, the timeline of a normal MPD startup is listed here:
- Since MPD is started as root by systemd, it first reads the
/etc/mpd.conf
file. - MPD reads the user variable in the
/etc/mpd.conf
file, and changes from root to this user. - MPD then reads the contents of the
/etc/mpd.conf
file and configures itself accordingly.
Notice that MPD changes the running user from root to the one named in the /etc/mpd.conf
file.
This way, uses of ~
in the configuration file point correctly to the home user's directory, and not root's directory.
It may be worthwhile to change all uses of ~
to /home/username
to avoid any confusion over this aspect of MPD's behavior.
Local configuration (per user)
MPD can be configured per user (rather than the typical method of configuring MPD globally). Running MPD as a normal user has the benefits of:
- A single directory
~/.config/mpd/
(or any other directory under$HOME
) that will contain all the MPD configuration files. - Easier to avoid unforeseen read/write permission errors.
Good practice is to create a single directory for the required files and playlists. It can be any directory for which you have read and write access, e.g. ~/.config/mpd/
or ~/.mpd/
. This section assumes it is ~/.config/mpd/
, which corresponds to the default value of $XDG_CONFIG_HOME
(part of XDG Base Directory Specification).
MPD searches for a config file in $XDG_CONFIG_HOME/mpd/mpd.conf
and then ~/.mpdconf
. It is also possible to pass other path as command line argument.
Copy the example configuration file to desired location, for example:
$ cp /usr/share/doc/mpd/mpdconf.example ~/.config/mpd/mpd.conf
Edit ~/.config/mpd/mpd.conf
and specify the required files:
~/.config/mpd/mpd.conf
# Required files db_file "~/.config/mpd/database" log_file "~/.config/mpd/log" # Optional music_directory "~/Music" playlist_directory "~/.config/mpd/playlists" pid_file "~/.config/mpd/pid" state_file "~/.config/mpd/state" sticker_file "~/.config/mpd/sticker.sql"
Create all the files and directories as configured above:
$ mkdir ~/.config/mpd/playlists $ touch ~/.config/mpd/{database,log,pid,state,sticker.sql}
When the paths of required files are configured, MPD can be started. To specify custom location of the configuration file:
$ mpd config_file
Автозапуск при входе на tty
Чтобы запустить MPD при входе, добавьте следующее в ~/.profile
(или другой автозапуск файла):
# MPD daemon start (if no other user instance exists) [ ! -s ~/.config/mpd/pid ] && mpd
Autostart in X
If you use a desktop environment, place the following file in ~/.config/autostart/
:
~/.config/autostart/mpd.desktop
[Desktop Entry] Encoding=UTF-8 Type=Application Name=Music Player Daemon Comment=Server for playing audio files Exec=mpd StartupNotify=false Terminal=false Hidden=false X-GNOME-Autostart-enabled=false
If you do not use a DE, place the line from #Autostart on tty login[broken link: invalid section] in your файле автозапуска.
Autostart with systemd
The package mpd provides user service file in /usr/lib/systemd/user/mpd.service
. The configuration file is expected to exist either in ~/.mpdconf
or ~/.config/mpd/mpd.conf
, see systemd#Editing provided units if you would like to use different path. The process is not started as root, so you should not use the user
and group
variables in the MPD configuration file, the process already has user permissions and therefore it is not necessary to change them further.
All you have to do is enable and start the mpd
user service[broken link: invalid section].
-
mpd provides also system service file in
/usr/lib/systemd/system/mpd.service
, but as the process is started as root, it does not read the user configuration file and falls back to/etc/mpd.conf
. Global configuration[broken link: invalid section] is described in other section. - Make sure to disable every other method of starting mpd you used before.
Scripted configuration
Rasi has written a script that will create the proper directory structure, configuration files and prompt for the location of the user's Music directory; it can be downloaded here.
Multi-mpd setup
Useful if running an icecast server.
For a second MPD (e.g., with icecast output to share music over the network) using the same music and playlist as the one above, simply copy the above configuration file and make a new file (e.g., /home/username/.mpd/config-icecast
), and only change the log_file, error_file, pid_file, and state_file parameters (e.g., mpd-icecast.log
, mpd-icecast.error
, and so on); using the same directory paths for the music and playlist directories would ensure that this second mpd would use the same music collection as the first one e.g., creating and editing a playlist under the first daemon would affect the second daemon as well. Users do not have to create the same playlists all over again for the second daemon. Call this second daemon the same way from ~/.xinitrc
above. (Just be sure to have a different port number, so as to not conflict with the first mpd daemon).
Клиенты
Для использования mpd необходим отдельный клиент. Список клиентов можно просмотреть по ссылке mpd wiki. Основные приведены здесь:
Консольные
- mpc — Клиент, использующий для управления mpd-сервером интерпретатор командной строки
- ncmpc — Ncurses клиент для mpd
- ncmpcpp — Копия ncmpc с новыми возможностями, написанная на C++ (редактор тегов, поисковый движок)
- pms — Гибкий и доступный ncurses клиент
- http://pms.sourceforge.net/ || pmusAUR[ссылка недействительна: сохранено в aur-mirror]
- vimpc — Ncurses mpd-клиент с vi-подобным управлением
- http://sourceforge.net/projects/vimpc/ || vimpcAUR[ссылка недействительна: сохранено в aur-mirror]
Графические
- Ario — Многофункциональный GTK2 GUI клиент для mpd, вдохновленный Rhythmbox
- QmpdClient — GUI написанный под Qt 4.x
- Sonata — Элегантный Python GTK+ клиент
- gmpc — GTK2 интерфейс для Music Player Daemon. Разрабатывался как легковесный клиент, реализующий все возможности, предоставляемые MPD. Предоставляет несколько различных методов обозревания медиатеки. Расширяется плагинами.
- Cantata — Многофункциональный Qt4, Qt5 или KDE4 клиент для MPD, позволяющий гибко настроить интерфейс
Web
- Patchfork — Веб клиент для MPD, написанный на PHP и Ajax
- http://mpd.wikia.com/wiki/Client:Pitchfork || patchfork-gitAUR[ссылка недействительна: сохранено в aur-mirror].