radiorec/radiorec.py

77 lines
2.3 KiB
Python
Raw Normal View History

2013-09-11 10:46:47 +02:00
#!/usr/bin/env python3
2013-09-11 16:10:16 +02:00
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
2013-09-11 10:46:47 +02:00
2013-09-11 11:06:13 +02:00
"""
This script records internet radio streams. It can be used in conjunction
with "at" or "crontab".
"""
2013-09-11 10:46:47 +02:00
import argparse
import configparser
2013-09-13 21:34:41 +02:00
import os
import sys
2013-09-13 12:54:59 +02:00
import threading
2013-09-11 10:46:47 +02:00
import urllib.request
2013-09-13 21:34:41 +02:00
def check_args():
2013-09-13 12:54:59 +02:00
parser = argparse.ArgumentParser(description='This program records '
'internet radio streams.')
2013-09-12 15:23:00 +02:00
parser.add_argument('station', type=str, help='Name of the radio station '
2013-09-13 12:54:59 +02:00
'(see config file for a list)')
2013-09-13 21:34:41 +02:00
parser.add_argument('duration', type=check_duration,
2013-09-13 12:54:59 +02:00
help='Recording time in minutes')
parser.add_argument('name', nargs='?', type=str,
help='A name for the recording')
return parser.parse_args()
2013-09-13 21:34:41 +02:00
def check_duration(value):
2013-09-13 12:54:59 +02:00
try:
value = int(value)
except ValueError:
raise argparse.ArgumentTypeError('Duration must be a positive integer.')
if value < 1:
raise argparse.ArgumentTypeError('Duration must be a positive integer.')
else:
return value
2013-09-13 21:34:41 +02:00
def read_settings():
settings_base_dir = ''
if sys.platform == 'linux':
settings_base_dir = os.getenv('HOME') + os.sep + '.config' + os.sep + 'radiorec'
elif sys.platform == 'win32':
settings_base_dir = os.getenv('APPDATA') + os.sep + 'radiorec'
settings_base_dir += os.sep
config = configparser.ConfigParser()
config.read(settings_base_dir + 'settings.ini')
return dict(config.items())
def record(stoprec, streamurl):
2013-09-13 13:51:01 +02:00
target = open('./test.mp3', "wb")
2013-09-13 21:34:41 +02:00
conn = urllib.request.urlopen(streamurl)
2013-09-13 13:51:01 +02:00
#print(conn.getheader('Content-Type'))
while(not stoprec.is_set() and not conn.closed):
target.write(conn.read(1024))
2013-09-13 12:54:59 +02:00
def main():
2013-09-13 21:34:41 +02:00
args = check_args()
settings = read_settings()
streamurl = ''
try:
settings['STATIONS'][args.station]
except KeyError:
print('Unkown station name: ' + args.station)
return
2013-09-13 12:54:59 +02:00
stoprec = threading.Event()
2013-09-13 21:34:41 +02:00
recthread = threading.Thread(target = record,
args = (stoprec, streamurl), daemon = True)
2013-09-13 12:54:59 +02:00
recthread.start()
recthread.join(args.duration * 60)
2013-09-13 21:34:41 +02:00
2013-09-13 12:54:59 +02:00
if(recthread.is_alive):
stoprec.set()
2013-09-11 16:10:16 +02:00
if __name__ == '__main__':
main()