Skip to content

Instantly share code, notes, and snippets.

@merylldindin
Created April 6, 2020 01:22
Show Gist options
  • Save merylldindin/ccd3090f5a09449e26667663b159c218 to your computer and use it in GitHub Desktop.
Save merylldindin/ccd3090f5a09449e26667663b159c218 to your computer and use it in GitHub Desktop.
import json, base64, websocket
class Base64Encoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, bytes): return base64.b64encode(o).decode()
return json.JSONEncoder.default(self, o)
class Emitter:
def __init__(self, streaming_url):
self.url = streaming_url
def send(self, filepath, chunk_size=2048):
src = open(filepath, 'rb')
wss = websocket.create_connection(self.url)
# Send first event with initialization
wss.send(json.dumps({'event': 'start', 'format': 'ulaw'}))
# Send first packet
chk = src.read(chunk_size)
pkt = {'event': 'media', 'media': {'payload': chk}}
wss.send(json.dumps(chk, cls=Base64Encoder))
# Keep emitting packet until dried file
while chk:
chk = src.read(chunk_size)
pkt = {'event': 'media', 'media': {'payload': chk}}
wss.send(json.dumps(chk, cls=Base64Encoder))
# Send conclusion event
wss.send(json.dumps({'event': 'stop'}))
# Close file and connection
src.close()
wss.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment