Search code examples
xargsmplayer

sort, mplayer and xargs


I have a directory full of music files that I want to play in mplayer. I want to play these files in order of their track number which is the forth field (space separated) in their filename. I know I could do something like this:

ls | sort -nk4 | playlist

and then

mplayer -playlist playlist

but I would like to be able to do it without creating a playlist file. The best I have so far is

ls | sort -nk4 | xargs -I{} mplayer {}

This seems to work but I am unable to use any of the normal mplayer controls. I am curious if this is possible. It seems it should be as you can type

mplayer songA.flac songB.flac songC.flac...

and it works fine.


Solution

  • Once mplayer is after a pipe, its std input is connected to the pipe now and not your keyboard, so the mplayer's controls stop working - try this instead:

    eval mplayer $( printf "%q\n" * | sort -n -k4 )
    

    or if your ls has -Q (quote) option:

    eval mplayer $( ls -Q | sort -n -k4 )
    
    • However note that the best way is to use temp files as suggested. They offer more flexibility, avoid the quoting issues and you can remove them after you're done. Place them under /tmp.
    • The quoting specifier %q of printf quotes the filenames - songs' names can have all kinds of characters in them.
    • eval is need to strip the extra layer of quoting, so mplayer sees just the properly quoted filename.

    Kinda messy as you see, so I'd again recommend using temp files ( been there, done that :).