Music Player Daemon (Español)

From ArchWiki
Revision as of 23:47, 27 December 2009 by Pwd (Talk | contribs) (Permisos de archivos y directorios: expandido un poco)

Jump to: navigation, search

Template:I18n links start Template:I18n entry Template:I18n entry Template:I18n entry Template:I18n entry Template:I18n entry Template:I18n entry Template:I18n entry Template:I18n entry Template:I18n links end


Tango-document-new.pngThis article is a stub.Tango-document-new.png

Notes: please use the first argument of the template to provide more detailed indications. (Discuss in Talk:Music Player Daemon (Español)#)
Note: Este artículo está incompleto. Ahora mismo está siendo traducido desde su versión en ingles

¿Qué es MPD?

MPD (Music Player Daemon) es un reproductor de audio que maneja una arquitectura servidor-cliente. mpd se ejecuta en el fondo como un daemon, gestiona listas de reproducción y una base de datos, y hace uso de muy pocos recursos. Para hacer uso de una interfaz gráfica, es necesario un cliente adicional. Más información puede obtenerse en su página web.

Procedimiento de Instalación del Daemon

Actualice e instale con pacman:

# pacman -S mpd

Ahora, añada el usuario mpd al grupo users:

# gpasswd -a mpd users

Instrucciones de Configuración

Para más información de la configuración de mpd, por favor visite http://mpd.wikia.com/wiki/Configuration

Linea de Tiempo del comportamiento habitual de mpd

  • mpd es iniciado al cargar el sistema operativo por medio de Template:Filename, incluyéndole en el apartado DAEMONS. (O, esto puede ser hecho manualmente ejecutando Template:Codeline con privilegios de root).
  • Al ser iniciado mpd como root, leerá el archivo Template:Filename.
  • mpd lee la variable usuario en el archivo Template:Filename, y cambia de root a este usuario.
  • mpd continúa leyendo el contenido del archivo Template:Filename y se configura de acuerdo a este.

Recuerde que mpd cambia el usuario de root a aquel mencionado en el archivo Template:Filename. Siendo asi, el uso de "~" en el archivo de configuracion hace referencia al directorio home del usuario, y no al directorio de root. Podria ser de utilidad cambiar todos los "~" a "/home/username" para prevenir cualquier confusion sobre este aspecto del comportamineto de mpd.

Un Archivo de Configuracion Limpio

  • Como root, verifique si Template:Filename existe y elimine el archivo en caso de que exista. Esto es hecho por seguridad.

Mpd viene con un ejemplo del archivo de configuracion, disponible en Template:Filename. Este archivo contiene abundante informacion acerca de la configuracion de mpd, y contiene valores predeterminados para el mixer, que simplemente pueden ser descomentados.

# cp /etc/mpd.conf.example /etc/mpd.conf

Nunca ponga este archivo en su directorio home como algunos tutoriales sugieren. Esto podria complicarlo todo, y la mayoria de las veces no tendra ningun sentido (recuerde que esta es una guia corta de instalacion y configuracion). Si creó con anterioridad un archivo Template:Filename en su directorio home, eliminelo ahora. Esto es importante para evitar conflictos. Cuando está ubicado en /etc, como se indica aqui, mpd podra ser ejecutado como daemon al inicio. De otro modo, un script sería necesario para ejecutar mpd LUEGO de que el usuario inicie sesion (Como kdm o ~/.fluxbox/startup), o tambien sera necesario una ejecucion manual. Para una coleccion musical unica, el metodo utilizado aqui es mejor, aún si la coleccion es compartida entre multiples usuarios. Además, no se preocupe por los privilegios de root: aunque mpd es ejecutado como daemon, nunca lo hace completamente como root puesto que automaticamente pierde sus privilegios luego de ser ejecutado.

Sound Setup Correctly

To make audio output actually work ensure that you have setup audio card and mixer correctly. See ALSA. Do not forget to unmute the required channels in alsamixer, raise the volume and save changes with alsactl store. See Template:Filename if it still doesn't work.

Make sure your card can do hardware mixing (most of them can, including onboard audio). Or else this could cause problems with multiple sound playback. For example, this can prevent Mplayer from playing back sound while the mpd daemon is running, returning an audio error message stating the device is busy.

Editando Template:Filename

Para editar el archivo, como root:

# SUEDITOR /etc/mpd.conf

Mantiene la configuración en /var y usa "mpd" como usuario por defecto en vez de atestar ~/. Este es el modo en que el paquete es instalado en Arch.

Edite Template:Filename para verse de la siguiente manera.

music_directory       "/home/usuario/música"         # Su directorio de música.
playlist_directory    "/var/lib/mpd/playlists"
db_file               "/var/lib/mpd/db"
log_file              "/var/log/mpd/mpd.log"
error_file            "/var/log/mpd/mpd.error"
pid_file              "/var/run/mpd/mpd.pid"
state_file            "/var/lib/mpd/mpdstate"
user                  "mpd"
# Ediciones a la dirección y el puerto causan problemas en mpd-0.14.2 es preferible dejarlos
# comentados.
# bind_to_address       "127.0.0.1"
# port                  "6600"

Lea con cuidado los pasos a continuación, los permisos deben ser otorgados correctamente.

  • Mantenga el usuario como "mpd", asegúrese que el directorio home del usuario "mpd" sea /var/lib/mpd
$ cat /etc/passwd | grep mpd
  • Además asegúrese que el directorio /var/lib/mpd sea propiedad de mpd:mpd.
$ ls -l /var/lib/ | grep mpd
  • Ahora como root, cree los archivos especificados en {Filename|/etc/mpd.conf}}, si los directorios no existen también deben ser creados. Esto no es necesario si hace uso de los predeterminados por el paquete de Arch.
# touch /var/lib/mpd/db
# touch /var/lib/mpd/mpdstate
# touch /var/run/mpd/mpd.pid
# touch /var/log/mpd/mpd.log
# touch /var/log/mpd/mpd.error
  • Ahora cambie el propietario de los directorios y archivos que ha creado, al usuario "mpd"
# chown -R mpd:mpd /var/{lib,run,log}/mpd
  • Si su colección musical está contenida en múltiples directorios, puede crear enlaces simbólicos en /var/lib/mpd y luego dirigir la variable 'music_dir' en mpd.conf a el directorio que contiene los enlaces. Recuerde asignar los permisos correctamente en los directorios enlazados.
  • Crear la base de datos ahora es realizado por medio de la opción "update" del cliente, por ejemplo, si ejecuta ncmpcpp, por medio de la tecla 'U'.
    • El método anterior, crear la base de datos de mpd como root (# mpd --create-db), es obsoleto.

Configuración Alterna

MPD no necesita ser iniciado con permiso de root. La única razón por la cual MPD necesita ser iniciado como root (siendo llamado por medio de Template:Filename) es porque los archivos y directorios mencionados por defecto en el archivo de configuración son propiedad de root (el directorio /var). Una menos común, pero quizás mas sensible configuración, consiste en hacer que MPD trabaje con archivos y directorios que sean propiedad de un usuario normal. Ejecutar MPD como un usuario normal tiene varias ventajas:

  1. Puede manejar un solo directorio ~/.mpd (o cualquier otro directorio bajo /home/usuario) para todos los archivos de configuración de MPD
  2. No hay errores de lectura/escritura
  3. llamado más flexible a MPD haciendo uso de Template:Filename en vez de incluir 'mpd' en la sección de DAEMONS en Template:Filename.

Los siguientes pasos indican como iniciar MPD com oun usuario normal. Nota: este método no funcionará si múltiples usuarios desean acceder a MPD.

  • Copie el contenido del archivo de configuración por defecto de MPD, ubicado en Template:Filename a su directorio home. Un buen lugar sería Template:Filename.
  • Siga los pasos de la configuración anterior, ignorando la primer parte, que hace referencia a copiar el archivo de configuración a Template:Filename.
  • Cree todos los archivos necesarios en Template:Filename:
"~/.mpd/playlists"
"~/.mpd/db"
"~/.mpd/mpd.log"
"~/.mpd/mpd.error"
"~/.mpd/mpd.pid"
"~/.mpd/mpdstate"
# esto inicia MPD como un usuario normal
mpd /home/username/.mpd/config
Note: no tiene que poner un "&" al final de la linea, dado que MPD automáticamente se daemonizará.

Finalmente, elimine mpd de la sección de DAEMONS en Template:Filename, ya que no será ejecutado como root nunca más.

Configuración Multi-MPD

Útil si desea ejecutar un servidor icecast, por ejemplo. Si desea un segundo daemon MPD (ej., con una salida icecast para compartir su música a través de una red) que haga uso de la música y listas de reproducción del primero, simplemente copie el archivo de configuración anterior y cree uno nuevo (ej., Template:Filename), y solo cambie los parámetros de log_file, error_file, pid_file, y state_file (ej., Template:Filename, Template:Filename, y demás); hacer uso de los mismos directorios de música y listas de reproducción asegurará que este segundo daemon MPD hará uso de la misma colección musical del primero (ej., crear y editar una lista de reproducción bajo el primer daemon afectará también al segundo daemon, de modo que no sea necesario crear la misma lista de nuevo para el segundo daemon). Finalmente, ejecute este segundo daemon por medio de su archivo Template:Filename. (Asegúrese de utilizar un numero de puerto diferente, para evitar conflictos con su primer daemon MPD).

Solución de Problemas

Autodetección Fallida

Durante el inicio de mpd, el intentará detectar automaticamente y configurar su salida de audio y control de volumen. Aunque en la mayoria de los casos esto suele funcionar, en otros sistemas puede fallar. Podria ser de ayuda para mpd especificar que utilizar como salida y mixer de sonido. Si su archivo Template:Filename es una copia de Template:Filename como se menciono anteriormente, simplemente descomente estas lineas:

Ejemplo de una salida tipo ALSA:

audio_output {
	type			"alsa"
	name			"My ALSA Device"
	device			"hw:0,0"	# optional
	format			"44100:16:2"	# optional
}

Ejemplo del mixer ALSA:

mixer_type			"alsa"
mixer_device			"default"
mixer_control			"PCM"

Nota: en caso de problemas con los permisos cuando utilize ESD, ejecute esto como root:

# chsh -s /bin/true mpd

Permisos de archivos y directorios

Warning: Estas direcciones se prestan a problemas de seguridad.

MPD necesita tener permiso para ejecutar los directorios que conforman tu coleccion de musica. Ademaz, el comando Template:Codeline asigna permisos 1700 drwx------ para el directorio principal de el usuario, significando que tendras que cambiar el acceso designado a Template:Filename para que MPD pueda funcionar correctamente. Suponiendo que la coleccion en cuestion se ubica en:

$ /home/usuario/musica

los comandos correctos serian:

$ chmod a+x /home/usuario
$ chmod -R g+X /home/usuario/musica

Solucion alternativa

Otra opcion seria usar tu grupo como forma para compartir archivos selectos, entre ellos tu coleccion de musica. Primero quita todos los permisos de grupo actualmente asignados para luego establecer el nuevo esquema:

$ chmod -R g-rwx /home/user
$ chmod g+rx /home/user
$ chmod -R g+rX /home/user/music

Tips

To get rid of timeouts (i.e. when you paused music for long time) in gpmc and other clients uncomment and increase Template:Codeline option in Template:Filename.

If files and/or titles are shown in wrong encoding, uncomment and change Template:Codeline and Template:Codeline options. Note that you cannot set encoding for ID3 v2 tags. To workaround this you may use external tag readers.

If you want to use another computer to control mpd over a network, the Template:Codeline option in Template:Filename will need to be set to either your IP address, or Template:Codeline if your IP address changes frequently. Remember to add mpd to the Template:Filename file to enable external access.

Streaming

With the latest version of mpd (0.15), built-in httpd streaming is now available.

To activate this feature, you'll just need to add a new output of type httpd in Template:Filename:

 audio_output {
           type   "httpd"
           name   "What you want"
           encoder "lame"     # vorbis or lame supported
           port    "8000"
           bitrate  "128"
           format   "44100:16:2"  # change 2 to 1 for mono
   }
     

Restart the mpd deamon and, from another computer, simply load the stream as any other url.

 mplayer http://<server's IP>:8000

Most players (i.e. vlc or xmms2) should also be able to load the stream via their "add url..." menu option.

This is a nice clean way to replace your current icecast setup with something natively supported within MPD.

Client Install Procedure

Install a client program for mpd. Popular options are:

Install with:

# pacman -Sy mpc
# pacman -Sy ncmpc
# pacman -Sy ncmpcpp
# pacman -Sy pms
# pacman -Sy ario
# pacman -Sy sonata
# pacman -Sy gmpc
# pacman -Sy qmpdclient

Extra stuff

Last.fm scrobbling

To scrobble your songs to Last.fm using MPD there are several alternatives.

mpdscribble

mpdscribble is another daemon, but is only available in the AUR. This is arguably the best alternative, because it's the semi-official MPD scrobbler and uses the new "idle" feature in MPD for more accurate scrobbling. Also, you don't need root access to configure it, because it doesn't need any changes to /etc at all. Visit the official website for more information.

To install mpdscribble, just install it from the AUR and do the following (not as root):

username = <your last.fm username>
password = <md5 sum of your last.fm password> # Generated using "echo -n password | md5sum"
host = <your mpd host> # defaults to $MPD_HOST or localhost
port = <your mpd port> # defaults to $MPD_PORT or 6600
log = ~/.mpdscribble/mpdscribble.log
journal = ~/.mpdscribble/mpdscribble.cache
verbose = 2
sleep = 1
musicdir = <your music directory>

Sonata

The easiest way, if you don't care about having to have a program window open all the time, is using Sonata which is a graphical frontend to MPD. It has built-in support for Last.fm scrobbling in its preferences. The downside of this is that Sonata doesn't cache your songs if for some reason you don't happen to have an Internet connection at the time of playing.

lastfmsubmitd

lastfmsubmitd is a daemon which is available in the "community" repository. To install it, first edit Template:Filename and add both Template:Codeline and Template:Codeline to the Template:Codeline array in Template:Filename.

Last.fm playback with lastfmproxy

lastfmproxy is a python script that streams a last.fm music stream to another media player. To setup, install from AUR: Template:Codeline and then edit Template:Filename. If you plan to only stream to mpd on the same host, just edit the login info.

Note: Since it installs to a read only directory but it requires read/write access for features like saving previously listened to stations, it would be wise to copy Template:Filename to your home directory.

Start lastfmproxy with Template:Codeline and visit http://localhost:1881/ in your web browser. To add a last.fm station navigate to http://localhost:1881/ followed by the lastfm:// url. Example: http://localhost:1881/lastfm://globaltags/punk . Navigate back to http://localhost:1881/ and download the m3u file by selecting the Start Listening link. Simply add it to your music library path.

Never play on start

If you don't want mpd to always play on your system start, but yet you want to preserve the other state information, add the following lines to your Template:Filename file:

   ...
   stat_busy "Starting Music Player Daemon"
   # always start in paused state
   awk '/^state_file[ \t]+"[^"]+"$/ {
       match($0, "\".+\"")
       sfile = substr($0, RSTART + 1, RLENGTH - 2)
   } /^user[ \t]+"[^"]+"$/ {
       match($0, "\".+\"")
       user = substr($0, RSTART + 1, RLENGTH - 2)
   } END {
       if (sfile == "")
               exit;
       if (user != "")
               sub(/^~/, "/home/" user, sfile)
       system("sed -i \x27s|^\\(state:[ \\t]\\{1,\\}\\)play$|\\1pause|\x27 \x27" sfile "\x27")
   }' /etc/mpd.conf
   /usr/bin/mpd /etc/mpd.conf &> /dev/null
   ...

This will change the player status to "paused", if it was stopped while playing. Next, you want this file to be preserved, so mpd updates won't erase this edit. Add (or edit) this line to your Template:Filename:

NoUpgrade = etc/rc.d/mpd

Or Simple method add mpd to your rc.conf deamons array and add mpc stop to rc.local loacated in /etc (Remember you must got mpc installed to have this method working).

MPD & Alsa

Sometimes, when you use other audio output, e.g: some web pages containing Flash applets, mpd cannot reproduce anything anymore (until you restart). The error looks something like: (if you search the file Template:Filename)

Error opening alsa device "hw:0,0": Device or resource busy

And here is the solution (dmix saving our life again). Apply these lines in your Template:Filename:

audio_output {
        type                    "alsa"
        name                    "Sound Card"
        options                 "dev=dmixer"
        device                  "plug:dmix"
}

And then restart with Template:Codeline.

Searching on Internet I found the reason for why that happens in Gentoo's wiki:

  • The sound card does not support hardware mixing (uses dmix plugin)
  • An application does not work with ALSA with it's default settings

High CPU usage with ALSA

When using MPD with ALSA, users may experience MPD taking up lots of CPU (around 20-30%). This is caused by most sound cards supporting 48kHz and most music being 44kHz, thus forcing MPD to resample it. This operation takes lots of CPU cycles and results into high usage.

For most users the problem should be solved by telling MPD not to use resampling by adding Template:Codeline into audio_output-part of Template:Filename.

Example from Template:Filename:

audio_output {
   type			"alsa"
   name			"My ALSA Device"
   auto_resample		"no"
}

Some users might also want to tell dmix to use 44kHz as well. More info about tuning performance of your MPD can be found from: MPD wiki

Control mpd with lirc

There are already some clients designe for communications between lircd and mpd, however, as far as the practical use, they aren't very useful since their functions are limited.

It's recommended to use mpc with irexec. mpc is a command line player which only sends the command to mpd and exits immediately, which is perfect for irexec, the command runner included in lirc. What irexec does is that it runs a specified command once received a remote control button.

First of all, please setup your remotes as referred to the Lirc article.

Edit your favored lirc startup configuration file, default location is Template:Filename.

Fill the file with the following pattern:

begin
     prog = irexec
     button = <button_name>
     config = <command_to_run>
     repeat = <0 or 1>
end

An useful example:

## irexec
begin
     prog = irexec
     button = play_pause
     config = mpc toggle
     repeat = 0
end

begin
     prog = irexec
     button = stop
     config = mpc stop
     repeat = 0
end
begin
     prog = irexec
     button = previous
     config = mpc prev
     repeat = 0
end
begin
     prog = irexec
     button = next
     config = mpc next
     repeat = 0
end
begin
     prog = irexec
     button = volup
     config = mpc volume +2
     repeat = 1
end
begin
     prog = irexec
     button = voldown
     config = mpc volume -2
     repeat = 1
end
begin
     prog = irexec
     button = pbc
     config = mpc random
     repeat = 0
end
begin
     prog = irexec
     button = pdvd
     config = mpc update
     repeat = 0
end
begin
     prog = irexec
     button = right
     config = mpc seek +00:00:05
     repeat = 0
end
begin
     prog = irexec
     button = left
     config = mpc seek -00:00:05
     repeat = 0
end
begin
     prog = irexec
     button = up
     config = mpc seek +1%
     repeat = 0
end
begin
     prog = irexec
     button = down
     config = mpc seek -1%
     repeat = 0
end

There are more functions for mpc, run Template:Codeline for more info.

Control mpd with bluetooth phone

You can also control mpd (to a certain extent) using a bluetooth enabled phone. You need to do the following:

  • install remuco -- a wireless remote control for several Linux media players (aur)
  • transfer remuco client -- jar/jad files from Template:Filename to your phone and install it
  • run Template:Codeline (as current user)
  • run remuco on your phone, define a new bluetooth remuco connection (pair first if you haven't done this previously) and explore its capabilities

More information about remuco including troubleshooting to be found at its homepage

MPD & PulseAudio

First, install (mpd-pulse) in the Arch User Repository as opposed to the regular mpd client in the Extra repository.

Then, edit Template:Filename, and uncomment the audio_output section for the type "pulse". The server and sink lines of it should be commented unless you know what you're doing.

Then, add the mpd user (and yours if you haven't done so already) to the necessary pulse groups. The pulse-access group should be sufficient but you may want to add pulse-rt as well. The group "pulse" doesn't appear to be necessary.

# gpasswd -a mpd pulse-access
# gpasswd -a mpd pulse-rt

Lastly, you may or may not need to copy Template:Filename from your current (pulse working) user's dir to your mpd user's home directory. It is likely to be Template:Filename if you followed the first part of this wiki. This would probably only allow your current user to listen in on mpd's pulse. You may consider running pulse system-wide if that's insufficient.

Troubleshooting

mpd --create-db hangs

This is a common error that's caused by corrupt mp3 tags. Here is an experimental way to solve this issue. Requirements:

  • kid3
  • easytag

This method is very tedious, expecially with a huge database. Just as a baseline it took 2.5h to fix a 16Gb DB.

Easy Tag

The purpose of easytag here is that easytag detects the error in the tags, but like mpd it hangs and dies. The trick here is that easy tags actually tells you what file is causing the problem on the status bar. Before starting easytag make sure to have a terminal close to be ready to kill easy tag to avoid a hang. Once you are ready, on the tree view select the directory where all your music is located. By default easytag starts to search all subdirectories for mp3 files. Once you notice that easytag stopped scanning for songs, make note of the culprit and kill easytag.

KID3

Here's where kid3 comes in handy. With kid3 go to the offending song and rewrite one of the tags. then save the file. This should force kid3 to rewrite the whole tag again fixing the problem with mpd and easy tag hanging.

Repeat this procedure until your music library is done.

Cannot connect to mpd: host "localhost" not found: Temporary failure in name resolution

Cannot connect to mpd (with ncmpcpp), if you are disconnected from network. Solution is disable IPv6 or add line to /etc/hosts

::1 localhost.localdomain localhost

Port 6600 already in use

MPD needs to bind to port 6600 and cannot start if it's already in use. The most common reason for this is that the user has started mpd once and then subsequently tried mpd --create-db. New mpd behavior is the --create-db option also attempts to start the daemon; if it's already been started, this will fail. If this is the case, try the following:

$ mpd --kill
$ mpd --create-db

A more brute-force approach:

$ killall mpd
$ mpd --create-db
Note: If you typically run mpd as root, you will need to run the above commands as root.

In the git version of mpd, --create-db is completely deprecated. The database will be created automagically on first run and can subsequently be updated via your client (i.e. mpc update). Eventually, inotify support will offer fully automatic database updates as you add content to your music folders

If port 6600 is tied up for some other reason, one can use the following command to find the offending process:

 # netstat -tulpan | grep 6600

This will list IP:Port and the process name holding the connection (root privileges are required to see all processes).

Crackling sound with some audio files

This is usually a playback speed problem and can be fixed by uncommenting the audio_output_format line in:

Template:File

This is usually a sane value for most mp3 files.

External links