A Python library and example script that downloads an audio file via youtube-dl and streams it to an IceCast server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.2 KiB

#!/usr/bin/env python3
import pathlib, os, sys, traceback, configparser
from yt_dlp import YoutubeDL
from shout import Shout
class IceDJ:
def __init__(self):
config = configparser.ConfigParser()
config.read('config.txt')
cfgShout = config['IceDJ-shout']
self.shout = Shout()
self.shout.host = cfgShout['host']
self.shout.port = int(cfgShout['port'])
self.shout.user = cfgShout['user']
self.shout.password = cfgShout['password']
self.shout.mount = cfgShout['mount']
self.ydl_opts = {
'format': 'bestaudio',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'vorbis',
}],
'quiet': True
}
self.directory = 'icedj-files'
pathlib.Path(self.directory).mkdir(parents=True, exist_ok=True)
os.chdir(self.directory)
# TODO: check if url is valid
# downloads a url to a file and returns it's filename
def download(self, url):
try:
with YoutubeDL(self.ydl_opts) as ydl:
url = url.strip()
info = ydl.extract_info(url, download=False)
print(f"Downloading {info['title']} by {info['uploader']}")
filename = ydl.prepare_filename(info)
# replace extension with .ogg
filename = os.path.splitext(filename)[0] + '.ogg'
ydl.download([url])
print(f"Downloaded to: {filename}")
return filename
except Exception:
traceback.print_exc()
# read bytes from file and send to icecast server
def stream(self, filename):
self.shout.open()
print(f'Streaming file: {filename}')
f = open(filename, 'rb')
self.shout.set_metadata({'song': filename})
nbuf = f.read(4096)
total = 0
while True:
buf = nbuf
nbuf = f.read(4096)
total += len(buf)
# at end of file
if len(buf) == 0:
break
self.shout.send(buf)
self.shout.sync()
f.close()
self.shout.close()
print(f'Finished streaming file: {filename}')