1

I want to stream a file (mp3) in python. I've written the server code (which doesn't work):

import socket

HOST = ''
PORT = 8888

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.bind((HOST, PORT))
print 'Socket bind complete'
s.listen(1)
print 'Socket now listening'
conn, addr = s.accept()
data = open("song.mp3", "rb")
data = data.read()
conn.sendall(data)

I haven't written a client for it, as I wanted to make it work with VLC, Chrome and other music players. When trying in VLC it gives me a "Connection reset by peer" error, whereas in Chrome it gives a "Broken pipe" error.

What I'm trying to do is make a basic replica of AirPlay, but I don't know what's wrong.

user2563892
  • 553
  • 1
  • 7
  • 16

2 Answers2

1

Have a look at this Playing remote audio files in Python? The mp3 format was designed for streaming, which makes some things simpler than you might have expected. The data is essentially a stream of audio frames with built-in boundary markers, rather than a file header followed by raw data, have a look at following url for more information. Writing a Python Music Streamer

Community
  • 1
  • 1
NIlesh Sharma
  • 5,445
  • 6
  • 36
  • 53
  • Yes, but I wanna know how to do it in general with files. I mean at least with videos and photos, cause that's what AirPlay does. I just wanna learn how I can open a port and kind of redirect it to the local source, I mean like a man in the middle local source -> Python -> Internet – user2563892 Jun 09 '14 at 10:41
0

OK, I got it to work with VLC by using HTTP here's the code:

import socket

filePath = "/storage/sdcard0/Music/song.mp3"
fileData = open(filePath, "rb").read()
host = ''
port = 8808
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HTTPString = "HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Type: audio/mpeg\r\n\r\n" + fileData
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
conn.sendall(HTTPString)

UPDATE: Got it to work with Chrome's (never thought I'd say this) stupid persistent connections, which raise SIGPIPE, so I just ignore it:

import socket

filePath = "/storage/sdcard0/Music/Madonna - Ray Of Light.mp3"
fileData = open(filePath, "rb").read()
host = ''
port = 8808
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HTTPString = "HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Type: audio/mpeg\r\n\r\n" + fileData

s.bind((host, port))

s.listen(10)
while 1:
    try:
        conn, addr = s.accept()
        conn.sendall(HTTPString)
    except socket.error, e:
        pass
user2563892
  • 553
  • 1
  • 7
  • 16