Search code examples
pythonubuntu-16.04vlclive-streaming

Saving audio from livestream using VLC library


I am trying to save audio clips (15 seconds per clip) from live stream using VLC library. I am unable to find any option that could allow me to record only 15 seconds from the live stream. Thus I ended up using timer in my code, but the recording clips sometimes contain 10 seconds, sometimes 20 seconds (rarely 15 seconds). Also, sometimes the audio content is repeated in the clips. Here is the code (I am a newbie so please guide me)

Code.py

import os
import sys
import vlc
import time

clipNumber = sys.argv[1]

filepath = 'http://streamer64.eboundservices.com/geo/geonews_abr/playlist.m3u8'
movie = os.path.expanduser(filepath)
if 'http://' not in filepath:
    if not os.access(movie, os.R_OK):
        print ( 'Error: %s file is not readable' % movie )
        sys.exit(1)
filename_and_command = "--sout=#transcode{vcodec=none,acodec=mp3,ab=320,channels=2,samplerate=44100}:file{dst=clip" + str(clipNumber) + ".mp3}"
#    filename_and_command = "--sout=file/ts:clip" + str(clipNumber) + ".mp3"
instance = vlc.Instance(filename_and_command)
try:
    media = instance.media_new(movie)
except NameError:
    print ('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1],
                    vlc.__version__, vlc.libvlc_get_version()))
    sys.exit(1)
player = instance.media_player_new()
player.set_media(media)
player.play()
time.sleep(15)
exit()

Now that I want to record 1 minute of the live-stream, I invoke this python code from the bash script 4 times and it creates 4 audio clips (clip1.mp3, clip2.mp3, clip3.mp3 and clip4.mp3)

Script.sh

for ((i=1; i<=4; i++))
do
    printf "Recording stream #%d\n", "$i"
    python code.py "$i"
    printf "Finished stream #%d\n", "$i"
done

Is there anyway to just loop the code with Python instead of invoking again and again with bash script (I tried to put the code in the loop in python, but the first clip - clip1 - keeps recording and never finishes recording). And a way to specify that I could only record 15 seconds from the live-stream instead of using time.sleep(15)


Solution

  • All of the work required can easily be done with FFMPEG as:

    ffmpeg -i streamURL -c copy -vn -ac 2 -acodec aac -t 15
    

    -vn for just recording the audio part (without video)

    -t for specifying the duration of stream you want to record (15 sec here)