Search code examples
pythontwistedm4atwisted.web

Python Twisted web server audio file


I am trying to create a simple web server with twisted in python. I am having trouble serving an m4a audio file though.

In the current program, when I load http://localhost:8880/mp3.html, it works fine. It shows the audio player and the mp3 plays. In addition, the program prints both "/mp3.html" and "/test.mp3".

However, when I load http://localhost:8880/m4a.html, it doesn't work. It shows the audio player, but the m4a doesn't play. In addition, the program prints only "/m4a.html" and not "/test.m4a".

My current code is below.

import urlparse
import os
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.web.static import File
import time
import subprocess
import mimetypes

class playM4A(Resource):
    isLeaf = True
    def render_GET(self, request):
        this=urlparse.urlparse(request.path)#scheme,netloc,path,query
        root,ext=os.path.splitext(this.path)
        filename=os.path.basename(request.path)
        fileFolder=request.path.replace(filename,"")
        self.serverRoot=os.getcwd()
        print request.path
        if ext==".m4a":
            thisFile=File(self.serverRoot+request.path)
            return File.render_GET(thisFile,request)
        elif ext==".mp3":
            thisFile=File(self.serverRoot+request.path)
            return File.render_GET(thisFile,request)
        elif filename=="m4a.html":
            return """
<html>
<audio controls>
  <source src="http://localhost:8880/test.m4a" type="audio/mp4a-latm">
Your browser does not support the audio element.
</audio>
not m4a </html>"""
        elif filename=="mp3.html":
            return """
<html>
<audio controls>
  <source src="http://localhost:8880/test.mp3" type="audio/mp3">
Your browser does not support the audio element.
</audio>
not m4a </html>"""

resource = playM4A()
factory = Site(resource)
reactor.listenTCP(8880, factory)
reactor.run()

Solution

  • The code works if you change audio/mp4a-latm to audio/mp4