使用mplayer定时录制网络电视/广播

匿名 (未验证), 20 二月, 2010

# !/bin/bash

# 参数1:录制时长。

# 重新启动mplayer的函数。
restartencode(){
echo "restart程序启动"
# 侦测现在的mplayer 的pid
mplayerpid_now=`ps -af | grep mplayer | grep cnr9 | awk '{ print $2 }'`
echo "原mplayer的pid : $1"
echo "现mplayer的pid : $mplayerpid_now"
mplayerpid=$mplayerpid_now
# 首先测试是否超过最大重试次数,然后测试是否有mplayer正在运行。
if [ "$try_times" -lt "try_limit" ]
then
if [ "$mplayerpid_now" ]
then
echo "不需重启mplayer"
else
audiofile="cnr9-$(date +'%Y%m%d-%T').rm.avi"
echo "重新启动mplayer"
mplayer $address -dumpstream -dumpfile ~/audio/$audiofile < /dev/null > /dev/null 2>&1 &
mplayerpid=$!
echo "新mplayer的pid : $mplayerpid"
let "try_times += 1"
echo "重试次数$try_times"
fi
else
echo "超出重试次数退出!"
exit
fi
}

# 录制时长
runtime=${1:-30m}
# 这个脚本的pid
mypid=$$
# Enable immediate notification of SIGCHLD
set -bm
# 录制文件名,文件名为“基名+时间”以免产生覆盖
audiofile="cnr9-$(date +'%Y%m%d-%T').rm.avi"
# 录制地址
address="rtsp://211.89.225.1:554/encoder/cnr9"
# mplayer缓冲cache设置,单位K
cache=32
# 网络连接重试次数
try_times=0
# 网络连接次数限定
try_limit=10

# 屏幕显示
echo "开始录制: $audiofile"
echo "开始时间: $(date +'%Y%m%d-%T')"
echo "录制时长: $1 "
echo "录制地址: $address"
echo "mplayer缓冲cache设置:$cache K"
echo "======================================="

# 利用mplayer进行录制,注意mplayer放入后台的用法。
mplayer -cache $cache $address -dumpstream -dumpfile ~/audio/$audiofile < /dev/null > /dev/null 2>&1 &

echo "mplayer -cache $cache $address -dumpstream -dumpfile $audiofile < /dev/null 2>&1 &"
echo "======================================="

# mplayer的pid
mplayerpid=$!
echo "初始mplayer的pid:$mplayerpid"

# mplayer在录制时长结束前退出,可能是网络问题。利用trap侦测信号,调用restart函数重启mplayer。
# Set a trap
trap "echo 'mplayer错误,重试,已经重试$try_times'" CHLD INT TERM KILL QUIT EXIT
trap "restartencode $mplayerpid" CHLD INT TERM KILL QUIT EXIT

# 开始计算录制时长前的缓冲时间,mplayer录制缓冲时间
sleep 10s
# Sleep for the specified time,录制持续时间控制。
sleep $runtime
sleeppid=$!

# Disable traps,trap复位
trap SIGCHLD
trap SIGINT
trap SIGTERM
trap SIGKILL
trap SIGQUIT
trap EXIT
trap TSTP

# 录制结束
mplayerpid_now=`ps -a | grep mplayer | awk '{ print $1 }'`
echo "现在mplayer进程$mplayerpid_now"
echo "中止mplayer进程$mplayerpid"
kill -15 $mplayerpid
echo "录制完成!"

评论