Tìm kiếm và tạo danh sách phát video dưới định dạng PLS, có thể dùng với phần mềm Kodi và các Media Player khác.
Đoạn mã sau hỗ trợ tìm kiếm và tạo playlist các video trong một thư mục được chỉ định theo định dạng PLS. Danh sách có thể được sắp xếp thứ tự theo tên, thời gian chỉnh sửa (modified time) hoặc thời lượng (duration) theo 2 chiều xuôi hoặc ngược.
gen_pls.sh
#!/bin/bash
order="name"
sort_args=""
valid_orders=(name date duration)
usage()
{
echo "Usage:"
echo " $(basename ${0}) [-o ORDER] [-r] <DIR...>"
echo " -o Sort by given ORDER"
echo " -r Sort in reversed ORDER"
echo " ORDER: name date duration"
exit
}
error()
{
echo "$@" >&2
}
# Check if an element exists in an array
contains()
{
local el
for el in "${@:2}"; do
if [[ "${el}" == "${1}" ]]; then
return 0
fi
done
return 1
}
print_from()
{
awk '{for(i='${1}';i<=NF;++i)printf $i""FS ; print ""}'
}
# Sorting order
order_by()
{
local sort_args=""
if [ "$2" = "reversed" ]; then
sort_args="-r"
fi
case "$1" in
name)
sort -n ${sort_args}
;;
date)
while read f; do
echo "$(stat -c %y "$f") $f"
done | sort -n ${sort_args} | print_from 4
;;
duration)
while read f; do
echo "$(mediainfo --Inform="Video;%Duration%" "$f") $f"
done | sort -n ${sort_args} | print_from 2
;;
esac
}
# Find all videos in a given directory
find_videos()
{
find "${1}" -type f -not -name "*.part" -exec file -N -i -- {} + | \
sed -n 's!: video/[^:]*$!!p'
}
while getopts "o:rh" opt 2>/dev/null; do
case ${opt} in
o)
order=${OPTARG,,}
if ! contains ${order} "${valid_orders[@]}"; then
error "Invalid order"
usage
fi
;;
r)
direction="reversed"
;;
h)
usage;;
*)
usage;;
esac
done
shift $((OPTIND-1))
count=1
# Mandatory header
echo "[playlist]"
# Dump the list of videos
for dir in "$@"; do
find_videos "${dir}" | \
order_by ${order} ${direction} | \
while read video; do
echo "File${count}=${video}"
count=$((count + 1))
done
done
Ví dụ tạo playlist cho Kodi có tên là test.pls từ các video trong thư mục ~/Videos, sắp xếp theo ngày tăng dần.
KODI_PLS_DIR=~/.kodi/userdata/playlists/video
gen_pls.sh -o date ~/Videos > ${KODI_PLS_DIR}/test.pls








