3

If I have a script that plays a file using mplayer and I stop the playback half way through, is there a way to store the playback position where it stopped?

Tomcomm
  • 233
  • 2
  • 6
  • 16

2 Answers2

0

Try this its quick and dirty but gives me the seconds of the played song after mplayer exited

mplayer your.mp3 | tr [:cntrl:] '\n' | bbe -e "s/\x0a\x5b\x4a//" | tail -n 4 | head -n 1 | cut -d ':' -f 2 | cut -d '(' -f 1

0800peter
  • 57
  • 2
  • I'm not sure why there was a down-vote on this answer. The approach here is probably the only way to get the playback position when mplayer was stopped. This will not work if mplayer is abnormally terminated though. – b_laoshi Nov 15 '18 at 06:23
0

It should be noted that this does almost the same thing as 0800peter's answer but without the need to install bbe. Essentially, this is a rewrite of that answer with a friendly interface. This answer also accounts for the event that mplayer is prematurely terminated (as in with pkill mplayer).

#!/bin/bash

# desc: Runs mplayer to play input file and returns seconds of playback when stopped
# input: 
#   arg1: path to audio file
#   arg2: pass either [seconds|timestamp]; default timestamp
# output: returns the timestamp or total seconds elapsed when playback stopped 
#   (ie. when mplayer terminated)
playAudioFile() {
    audioFile="$1"

    # if you need to modify mplayer switches, do so on the next line
    stopPos=$(mplayer "$audioFile" 2> /dev/null | tr [:cntrl:] '\n' | grep -P "A: +\d+\.\d\b" | tail -n1)

    # decide what to display
    if [ "$2" == "seconds" ]; then
        retval=$(awk '{print $2}' <<< "$stopPos")
    else
        retval=$(awk '{print $3}'  <<< "$stopPos" | tr -d '()')
    fi

    echo "$retval"
}

#example usage
path="$1"
stopPosition=$(playAudioFile "$path")
echo "$stopPosition"

My script, as it is, accepts the path to an audio file and when mplayer terminates (normally or abnormally), a timestamp or seconds elapsed is returned. If you opt to receive a timestamp, note that the timestamp will not have a placeholder for any unit with a value zero. In other words, 00:00:07.3 would be returned as 07.3 and 00:10:01.2 would be returned as 10:01.2
 

What if I want to send mplayer to the background?

If you want to be able to start mplayer and send it to the background and still be able to query for this information, you might want to take a look at a bash script I wrote for tracking playback status information. That script incorporates two functions called getElapsedTimestamp and getElapsedSeconds, both of which return the playback time even if mplayer has already terminated. To use these functions, the media file must be started with my playMediaFile function. This function can be called like this to start mplayer and send to background ...

playMediaFile "path/to/your/file" &
b_laoshi
  • 443
  • 6
  • 12