IPython.display.Audio cannot correctly handle `.ogg` file type?

拈花ヽ惹草 提交于 2019-12-05 13:56:24

Since no one gives a hint, I guess I'll have to work alone...

First look into the source code of IPython.display.audio: ipython/display.py at 48b01aadcbb6a53d2c77fa250c8a4344931c357c · ipython/ipython

def _repr_html_(self):
    src = """
            <audio controls="controls" {autoplay}>
                <source src="{src}" type="{type}" />
                Your browser does not support the audio element.
            </audio>
          """
    return src.format(src=self.src_attr(),type=self.mimetype, autoplay=self.autoplay_attr())

This is the code that generates html source code of audio control block, type is assigned from self.mimetype. And self.mimetype is derived from reload():

    if self.filename is not None:
        self.mimetype = mimetypes.guess_type(self.filename)[0]
    elif self.url is not None:
        self.mimetype = mimetypes.guess_type(self.url)[0]
    else:
        self.mimetype = "audio/wav"

It's obvious if mimetypes.guess_type("filename.ogg")[0] gets None, then we have type == None, which results an inactive audio control block.

From 18.7. mimetypes — Map filenames to MIME types — Python 2.7.12 documentation I learned that MIME types can be loaded from file or dynamically added with mimetypes.add_type(). It also said by default mimetypes will load from Windows registry. I tried to modify system-wide MIME type settings of .ogg with one small utility FileTypesMan - Alternative to 'File Types' manager of Windows but it did not reflect on mimetypes, so I guess I'll have to let it go.

At last I realized that a monkey patch before IPython.display.Audio was used will possibly work and it really does:

It may not be perfect to solve the problem, but at least it works. So be it for now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!