simpleguitk载入声音和图片文件遇到的几个问题

在本地用simpleguitk写游戏,用到一些图片和声音,在加载的时候,出现以下现象:

1)载入图片:

simplegui.load_image(url)

如果url为http://xxxxxxx/xxx.png这种网络资源形式,则没有问题,如果url为本地文件路径,则报错:IOError: cannot identify image file,无法加载

2)载入声音:

simplegui.load_sound(url)

如果url为网络资源形式,则只能载入ogg格式文件,如果为本地文件路径,ogg文件报错:pygame.error: OGG bitstream is not valid Vorbis stream!,mp3文件同样不能被识别


打开simpleguitk中的Image.py和Sound.py文件看了一下,源代码如下:

class Image(object):
    def __init__(self, url):
        from PIL import Image as PilImage
        if url.startswith('http'):
            image = urlopen(url).read()
        else:
            image = open(url).read()
        self._image = PilImage.open(io.BytesIO(image)).convert('RGBA')

class Sound(object):
    def __init__(self, url):
        import pygame
        self._channel = None
        if url.startswith('http'):
            soundfile = urlopen(url).read()
        else:
            soundfile = open(url).read()
        self._sound = pygame.mixer.Sound(io.BytesIO(soundfile))

可见,无论url为什么形式,源码中均采用io.BytesIO()对打开的文件进行预处理。于是将代码改成如下形式:

class Image(object):
    def __init__(self, url):
        from PIL import Image as PilImage
        if url.startswith('http'):
            image = urlopen(url).read()
            self._image = PilImage.open(io.BytesIO(image)).convert('RGBA')
        else:
            #image = open(url).read()
            self._image = PilImage.open(url).convert('RGBA')
        #self._image = PilImage.open(io.BytesIO(image)).convert('RGBA')


class Sound(object):
    def __init__(self, url):
        import pygame
        self._channel = None
        if url.startswith('http'):
            soundfile = urlopen(url).read()
            self._sound = pygame.mixer.Sound(io.BytesIO(soundfile))
        else:
            #soundfile = open(url).read()
            self._sound = pygame.mixer.Sound(url)
        #self._sound = pygame.mixer.Sound(io.BytesIO(soundfile))

也就是对本地文件不用io.BytesIO()来预处理,而是直接打开。

修改后,打开图片时能兼容网络资源和本地资源,打开声音时网络资源的mp3格式不能打开,本地资源ogg和mp3均可以。

至于io.BytesIO()带来了什么影响,目前尚未弄明白。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值