play mp3 without default player

孤人 提交于 2020-01-06 02:36:06

问题


I'm trying play mp3 without default player use, so I want try pyglet, but nothing works

import pyglet

music = pyglet.resource.media('D:/folder/folder/audio.mp3')
music.play()

pyglet.app.run()

I've tried it this way

music = pyglet.resource.media('D:\folder\folder\audio.mp3')

and like this:

music = pyglet.resource.media('D:\\folder\\folder\\audio.mp3')

but have this error

Traceback (most recent call last):
  File "C:\Users\User\AppData\Roaming\Python\Python35\site-packages\pyglet\resource.py", line 624, in media
    location = self._index[name]
KeyError: 'D:\folder\folder\audio.mp3'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/PC/PyCharm_project/0_TEMP.py", line 3, in <module>
    music = pyglet.resource.media('D:\folder\folder\audio.mp3')
  File "C:\Users\User\AppData\Roaming\Python\Python35\site-packages\pyglet\resource.py", line 634, in media
    raise ResourceNotFoundException(name)
pyglet.resource.ResourceNotFoundException: Resource "D:\folder\folder\audio.mp3" was not found on the path.  Ensure that the filename has the correct captialisation.

回答1:


It's because of the way you load the resource.
Try this code for instance:

import pyglet

music = pyglet.media.load(r'D:\folder\folder\audio.mp3')
music.play()

pyglet.app.run()

The way this works is that it loads a file and places it in a pyglet.resource.media container. Due to namespaces and other things, the code you wrote is only allowed to load resources from the working directory. So instead, you use pyglet.media.load which is able to load the resource you need into the current namespace (Note: I might be missusing the word "namespace" here, for lack of a better term without looking at the source code of pyglet, this is the best description I could come up with).

You could experiment by placing the .mp3 in the script folder and run your code again but with a relative path:

import pyglet

music = pyglet.resource.media('audio.mp3')
music.play()

pyglet.app.run()

But I'd strongly suggest you use pyglet.media.load() and have a look at the documentation



来源:https://stackoverflow.com/questions/36819585/play-mp3-without-default-player

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