问题描述
我想制作一个内存文件以在pygame混合器中使用.我的意思是这样的( http://www.pygame .org/docs/ref/music.html#pygame.mixer.music.load 它表示load()方法支持文件对象)
I want to make a in-memory file to use in pygame mixer. I mean something like that (http://www.pygame.org/docs/ref/music.html#pygame.mixer.music.load it says load() method supports file object)
import requests
from pygame import mixer
r = requests.get("http://example.com/some_small_file.mp3")
in_memory_file = file(r.content) #something like that
mixer.music.init()
mixer.music.load(in_memory_file)
mixer.music.play()
推荐答案
您可能正在从Python io
包中寻找BytesIO
或StringIO
类,这两个类均在 Python 2 和 Python 3 .它们提供了类似于文件的界面,您可以在代码中使用与真实文件进行交互的方式完全相同.
You are probably looking for BytesIO
or StringIO
classes from Python io
package, both available in python 2 and python 3. They provide a file-like interface you can use in your code the exact same way you interact with a real file.
StringIO
用于存储文本数据:
import io
f = io.StringIO("some initial text data")
BytesIO
必须用于二进制数据:
BytesIO
must be used for binary data:
import io
f = io.BytesIO(b"\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01\x01")
要存储MP3文件数据,您可能需要BytesIO
类.要将其从GET请求初始化到服务器,请按以下步骤操作:
To store MP3 file data, you will probably need the BytesIO
class. To initialize it from a GET request to a server, proceed like this:
import requests
from pygame import mixer
import io
r = requests.get("http://example.com/somesmallmp3file.mp3")
inmemoryfile = io.BytesIO(r.content)
mixer.music.init()
mixer.music.load(inmemoryfile)
mixer.music.play()
这篇关于如何在内存中创建文件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!