1

Hi guise.
Last night I tryed out the pygame with pyglet openal libraries. Everything went fine, But when i tryed to run it, It suddenly exited and i didn't get any errors. Any helps are a pritiated. Here's the script:

import pygame
import pygame.mixer
import time
import random
from pyglet.media.drivers.openal import lib_openal as al
from pyglet.media.drivers.openal import lib_alc as alc
import wave
import sys
import os
import ctypes

pygame.init();
pygame.display.set_caption("My App! ")
screen=pygame.display.set_mode([700,700])
screen.fill([255,255,255])
pygame.display.update()
mixer=pygame.mixer
mixer.init()
me=listener()
enemy=player()
enemy.position=(50,50,4)
esound=load_sound('tone5.wav')
me.position=(0,0,0)
enemy.add(esound)
enemy.loop=True
enemy.rolloff=0.01
me.hrtf=1
myx=0
myy=0
myz=0
sound=mixer.Sound("sound.ogg")
def game():
    while True:
        me.position=(myx,myy,myz)
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    sound.play()
                    myy+=1
                elif event.key == pygame.K_DOWN:
                    sound.play()
                    myy-=1
                elif event.key == pygame.K_RIGHT:
                    sound.play()
                    myx+=1
                elif event.key == pygame.K_LEFT:
                    sound.play()
                    myx-=1

                elif event.key == pygame.K_Q:
                    pygame.quit()
                    esound.delete()
                    enemy.stop()
                    me.delete()
                    enemy.delete()
                    exit()

game()
class listener(object):
    def __init__(self):
    #load device/context/listener
        self.device = alc.alcOpenDevice(None)
        self.context = alc.alcCreateContext(self.device, None)
        alc.alcMakeContextCurrent(self.context)

    #get list of available htrf tables
        self.hrtf_buffers = [alc.ALCint(),alc.ALCint*4,alc.ALCint()]
        alc.alcGetIntegerv(self.device,alc.ALC_NUM_HRTF_SPECIFIERS_SOFT, 1,self.hrtf_buffers[0])

    #attributes for device to set specified hrtf table
        self.hrtf_select = self.hrtf_buffers[1](alc.ALC_HRTF_SOFT,alc.ALC_TRUE,alc.ALC_HRTF_ID_SOFT,1)


#list number of available hrtf tables
    def _hrtf_tables(self):
        return self.hrtf_buffers[0].value


#assign hrtf table to device and soft reboot to take effect
    def _set_hrtf(self,num):
        if num == None:
            alc.alcResetDeviceSOFT(self.device, None)
        elif num >= 0 and num <= self.hrtf_buffers[0]:
            self.hrtf_select[3] = num
        #reset the device so the new hrtf settings take effect
            alc.alcResetDeviceSOFT(self.device, self.hrtf_select)


#confirm hrtf has been loaded and is enabled
    def _get_hrtf(self):
        alc.alcGetIntegerv(self.device,alc.ALC_HRTF_SOFT,1,self.hrtf_buffers[2])
        if self.hrtf_buffers[2].value == alc.ALC_HRTF_DISABLED_SOFT:
            return False
        elif self.hrtf_buffers[2].value == alc.ALC_HRTF_ENABLED_SOFT:
            return True
        elif self.hrtf_buffers[2].value == alc.ALC_HRTF_DENIED_SOFT:
            return False
        elif self.hrtf_buffers[2].value == alc.ALC_HRTF_REQUIRED_SOFT:
            return True
        elif self.hrtf_buffers[2].value == alc.ALC_HRTF_HEADPHONES_DETECTED_SOFT:
            return True
        elif self.hrtf_buffers[2].value == alc.ALC_HRTF_UNSUPPORTED_FORMAT_SOFT:
            return False


#set player position
    def _set_position(self,pos):
        self._position = pos
        x,y,z = map(int, pos)
        al.alListener3f(al.AL_POSITION, x, y, z)

    def _get_position(self):
        return self._position

#delete current listener
    def delete(self):
        alc.alcDestroyContext(self.context)
        alc.alcCloseDevice(self.device)

    position = property(_get_position, _set_position,doc="""get/set position""")
    hrtf = property(_get_hrtf, _set_hrtf,doc="""get status/set hrtf""")
    hrtf_tables = property(_hrtf_tables,None,doc="""get number of hrtf tables""")


#load and store a wav file into an openal buffer
class load_sound(object):
    def __init__(self,filename):
        self.name = filename
    #load/set wav file
        if len (sys.argv) < 2:
            print ("Usage: %s wavefile" % os.path.basename(sys.argv[0]))
            print ("    Using an example wav file...")
            dirname = os.path.dirname(os.path.realpath(__file__))
            fname = os.path.join(dirname, filename)
        else:
            fname = sys.argv[1]

        wavefp = wave.open(fname)
        channels = wavefp.getnchannels()
        bitrate = wavefp.getsampwidth() * 8
        samplerate = wavefp.getframerate()
        wavbuf = wavefp.readframes(wavefp.getnframes())
        self.duration = (len(wavbuf) / float(samplerate))/2
        self.length = len(wavbuf)
        formatmap = {
            (1, 8) : al.AL_FORMAT_MONO8,
            (2, 8) : al.AL_FORMAT_STEREO8,
            (1, 16): al.AL_FORMAT_MONO16,
            (2, 16) : al.AL_FORMAT_STEREO16,
        }
        alformat = formatmap[(channels, bitrate)]

        self.buf = al.ALuint(0)
        al.alGenBuffers(1, self.buf)
    #allocate buffer space to: buffer, format, data, len(data), and samplerate
        al.alBufferData(self.buf, alformat, wavbuf, len(wavbuf), samplerate)

#delete loaded sound
    def delete(self):
        al.alDeleteBuffers(1, self.buf)



#load sound buffers into an openal source player to play them
class Player(object):
#load default settings
    def __init__(self):
    #load source player
        self.source = al.ALuint(0)
        al.alGenSources(1, self.source)
    #disable rolloff factor by default
        al.alSourcef(self.source, al.AL_ROLLOFF_FACTOR, 0)
    #disable source relative by default
        al.alSourcei(self.source, al.AL_SOURCE_RELATIVE,0)
    #capture player state buffer
        self.state = al.ALint(0)
    #set internal variable tracking
        self._volume = 1.0
        self._pitch = 1.0
        self._position = [0,0,0]
        self._rolloff = 1.0
        self._loop = False
        self.queue = []

#set rolloff factor, determines volume based on distance from listener
    def _set_rolloff(self,value):
        self._rolloff = value
        al.alSourcef(self.source, al.AL_ROLLOFF_FACTOR, value)

    def _get_rolloff(self):
        return self._rolloff


#set whether looping or not - true/false 1/0
    def _set_loop(self,lo):
        self._loop = lo
        al.alSourcei(self.source, al.AL_LOOPING, lo)

    def _get_loop(self):
        return self._loop
     

#set player position
    def _set_position(self,pos):
        self._position = pos
        x,y,z = map(int, pos)
        al.alSource3f(self.source, al.AL_POSITION, x, y, z)

    def _get_position(self):
        return self._position
       

#set pitch - 1.5-0.5 float range only
    def _set_pitch(self,pit):
        self._pitch = pit
        al.alSourcef(self.source, al.AL_PITCH, pit)

    def _get_pitch(self):
        return self._pitch

#set volume - 1.0 float range only
    def _set_volume(self,vol):
        self._volume = vol
        al.alSourcef(self.source, al.AL_GAIN, vol)

    def _get_volume(self):
        return self._volume

#queue a sound buffer
    def add(self,sound):
        al.alSourceQueueBuffers(self.source, 1, sound.buf) #self.buf
        self.queue.append(sound)

#remove a sound from the queue (detach & unqueue to properly remove)
    def remove(self):
        if len(self.queue) > 0:
            al.alSourceUnqueueBuffers(self.source, 1, self.queue[0].buf) #self.buf
            al.alSourcei(self.source, al.AL_BUFFER, 0)
            self.queue.pop(0)

#play sound source
    def play(self):
        al.alSourcePlay(self.source)

#get current playing state
    def playing(self):
        al.alGetSourcei(self.source, al.AL_SOURCE_STATE, self.state)
        if self.state.value == al.AL_PLAYING:
            return True
        else:
            return False

#stop playing sound
    def stop(self):
        al.alSourceStop(self.source)

#rewind player
    def rewind(self):
        al.alSourceRewind(self.source)

#pause player
    def pause(self):
        al.alSourcePause(self.source)

#delete sound source
    def delete(self):
        al.alDeleteSources(1, self.source)

#Go straight to a set point in the sound file, uses 0.0-1.0 float value
    def seek(self,offset):
        al.alSourcei(self.source,al.AL_BYTE_OFFSET,int(self.queue[0].length * offset))

    rolloff = property(_get_rolloff, _set_rolloff,doc="""get/set rolloff factor""")
    volume = property(_get_volume, _set_volume,doc="""get/set volume""")
    pitch = property(_get_pitch, _set_pitch, doc="""get/set pitch""")
    loop = property(_get_loop, _set_loop, doc="""get/set loop state""")
    position = property(_get_position, _set_position,doc="""get/set position""")

Be careful that what you're saying, Just a word Can break your personality!

Thumbs up

2 (edited by Kyleman123 2017-03-27 15:28:58)

if your system is set just to run .py files with python by pressing enter in your file browser, it might not output an error. especially if it outputs those to the cmd prompt which will close ones python ends, then its gone forever.i always open a command prompt first and use:

python my script.py

this is obviously in the directory where your script is located. there are several options and flags you can run that with but that is the most basic use.

I don’t believe in fighting unnecessarily.  But if something is worth fighting for, then its always a fight worth winning.
check me out on Twitter and on GitHub

Thumbs up

3

Yes i know, and I do the same. But i don't get anything. At least nvda doesn't read any errors. Just it exits the app. I know something is mistaken, But don't know what!

Be careful that what you're saying, Just a word Can break your personality!

Thumbs up

4

hello
@kianoosh, look at your code, it might indented improperly after that while loop which makes your game exit, you must remove one tab character
(i didnt count your tab chars)

bitcoin address: 1LyQ3hziMC2DTnCtgM3V1zfuZ73P3CYT9P

Thumbs up

5 (edited by kianoosh 2017-03-27 22:22:38)

No amir. I have counted them and they are all set correctly. And either if that's what you said, python must show an error regarding that blocks are not correct something like that. So the problem is something else.

Be careful that what you're saying, Just a word Can break your personality!

Thumbs up

6

Does the Pyglet OpenAL example and Pygame mixer work individually? As the OpenAL examples I wrote require copy over certain Pyglet scripts to include the proper extensions. Your script seems to work alright with a few adjustments, such as in line 20 player() should be with a capitol P. You could try putting print statements along your script to see how far it gets when loading before crashing.

-BrushTone v1.2.8: Accessible Paint Tool

Thumbs up

7

Yes. I have copyed that into my openal location. And thanks for your help, Gonna do this now and will post the results here.

Be careful that what you're saying, Just a word Can break your personality!

Thumbs up

8

Hi again, I have fixed those things, I have added prints and stuff like that, But even nothing prints. Here is the code:
import pygame
import pygame.mixer
import time
import random
from pyglet.media.drivers.openal import lib_openal as al
from pyglet.media.drivers.openal import lib_alc as alc
import wave
import sys
import os
import ctypes
import pyglet
pygame.init()
pygame.display.set_caption("My App! ")
screen=pygame.display.set_mode([700,700])
screen.fill([255,255,255])
pygame.display.update()
mixer=pygame.mixer
mixer.init()
me=listener()
enemy=player()
enemy.position=(50,50,4)
esound=load_sound('tone5.wav')
enemy.add(esound)
enemy.loop=True
enemy.rolloff=0.01
me.hrtf=1
myx=0
myy=0
myz=0
sound=mixer.Sound("sound.ogg")
print "Veriables set"
enemy.play()
print "the enemy sound is playing"
print me.hrtf_tables
print me.hrtf
def game():
    while True:
        me.position=(myx,myy,myz)
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    sound.play()
                    myy+=1
                elif event.key == pygame.K_DOWN:
                    sound.play()
                    myy-=1
                elif event.key == pygame.K_RIGHT:
                    sound.play()
                    myx+=1
                elif event.key == pygame.K_LEFT:
                    sound.play()
                    myx-=1
                elif event.key == pygame.K_Q:
                    pygame.quit()
                    esound.delete()
                    enemy.stop()
                    me.delete()
                    enemy.delete()
                    exit()
class listener(object):
    def __init__(self):
    #load device/context/listener
        self.device = alc.alcOpenDevice(None)
        self.context = alc.alcCreateContext(self.device, None)
        alc.alcMakeContextCurrent(self.context)

    #get list of available htrf tables
        self.hrtf_buffers = [alc.ALCint(),alc.ALCint*4,alc.ALCint()]
        alc.alcGetIntegerv(self.device,alc.ALC_NUM_HRTF_SPECIFIERS_SOFT, 1,self.hrtf_buffers[0])

    #attributes for device to set specified hrtf table
        self.hrtf_select = self.hrtf_buffers[1](alc.ALC_HRTF_SOFT,alc.ALC_TRUE,alc.ALC_HRTF_ID_SOFT,1)


#list number of available hrtf tables
    def _hrtf_tables(self):
        return self.hrtf_buffers[0].value


#assign hrtf table to device and soft reboot to take effect
    def _set_hrtf(self,num):
        if num == None:
            alc.alcResetDeviceSOFT(self.device, None)
        elif num >= 0 and num <= self.hrtf_buffers[0]:
            self.hrtf_select[3] = num
        #reset the device so the new hrtf settings take effect
            alc.alcResetDeviceSOFT(self.device, self.hrtf_select)


#confirm hrtf has been loaded and is enabled
    def _get_hrtf(self):
        alc.alcGetIntegerv(self.device,alc.ALC_HRTF_SOFT,1,self.hrtf_buffers[2])
        if self.hrtf_buffers[2].value == alc.ALC_HRTF_DISABLED_SOFT:
            return False
        elif self.hrtf_buffers[2].value == alc.ALC_HRTF_ENABLED_SOFT:
            return True
        elif self.hrtf_buffers[2].value == alc.ALC_HRTF_DENIED_SOFT:
            return False
        elif self.hrtf_buffers[2].value == alc.ALC_HRTF_REQUIRED_SOFT:
            return True
        elif self.hrtf_buffers[2].value == alc.ALC_HRTF_HEADPHONES_DETECTED_SOFT:
            return True
        elif self.hrtf_buffers[2].value == alc.ALC_HRTF_UNSUPPORTED_FORMAT_SOFT:
            return False


#set player position
    def _set_position(self,pos):
        self._position = pos
        x,y,z = map(int, pos)
        al.alListener3f(al.AL_POSITION, x, y, z)

    def _get_position(self):
        return self._position

#delete current listener
    def delete(self):
        alc.alcDestroyContext(self.context)
        alc.alcCloseDevice(self.device)

    position = property(_get_position, _set_position,doc="""get/set position""")
    hrtf = property(_get_hrtf, _set_hrtf,doc="""get status/set hrtf""")
    hrtf_tables = property(_hrtf_tables,None,doc="""get number of hrtf tables""")


#load and store a wav file into an openal buffer
class load_sound(object):
    def __init__(self,filename):
        self.name = filename
    #load/set wav file
        if len (sys.argv) < 2:
            print ("Usage: %s wavefile" % os.path.basename(sys.argv[0]))
            print ("    Using an example wav file...")
            dirname = os.path.dirname(os.path.realpath(__file__))
            fname = os.path.join(dirname, filename)
        else:
            fname = sys.argv[1]

        wavefp = wave.open(fname)
        channels = wavefp.getnchannels()
        bitrate = wavefp.getsampwidth() * 8
        samplerate = wavefp.getframerate()
        wavbuf = wavefp.readframes(wavefp.getnframes())
        self.duration = (len(wavbuf) / float(samplerate))/2
        self.length = len(wavbuf)
        formatmap = {
            (1, 8) : al.AL_FORMAT_MONO8,
            (2, 8) : al.AL_FORMAT_STEREO8,
            (1, 16): al.AL_FORMAT_MONO16,
            (2, 16) : al.AL_FORMAT_STEREO16,
        }
        alformat = formatmap[(channels, bitrate)]

        self.buf = al.ALuint(0)
        al.alGenBuffers(1, self.buf)
    #allocate buffer space to: buffer, format, data, len(data), and samplerate
        al.alBufferData(self.buf, alformat, wavbuf, len(wavbuf), samplerate)

#delete loaded sound
    def delete(self):
        al.alDeleteBuffers(1, self.buf)



#load sound buffers into an openal source player to play them
class player(object):
#load default settings
    def __init__(self):
    #load source player
        self.source = al.ALuint(0)
        al.alGenSources(1, self.source)
    #disable rolloff factor by default
        al.alSourcef(self.source, al.AL_ROLLOFF_FACTOR, 0)
    #disable source relative by default
        al.alSourcei(self.source, al.AL_SOURCE_RELATIVE,0)
    #capture player state buffer
        self.state = al.ALint(0)
    #set internal variable tracking
        self._volume = 1.0
        self._pitch = 1.0
        self._position = [0,0,0]
        self._rolloff = 1.0
        self._loop = False
        self.queue = []

#set rolloff factor, determines volume based on distance from listener
    def _set_rolloff(self,value):
        self._rolloff = value
        al.alSourcef(self.source, al.AL_ROLLOFF_FACTOR, value)

    def _get_rolloff(self):
        return self._rolloff


#set whether looping or not - true/false 1/0
    def _set_loop(self,lo):
        self._loop = lo
        al.alSourcei(self.source, al.AL_LOOPING, lo)

    def _get_loop(self):
        return self._loop
     

#set player position
    def _set_position(self,pos):
        self._position = pos
        x,y,z = map(int, pos)
        al.alSource3f(self.source, al.AL_POSITION, x, y, z)

    def _get_position(self):
        return self._position
       

#set pitch - 1.5-0.5 float range only
    def _set_pitch(self,pit):
        self._pitch = pit
        al.alSourcef(self.source, al.AL_PITCH, pit)

    def _get_pitch(self):
        return self._pitch

#set volume - 1.0 float range only
    def _set_volume(self,vol):
        self._volume = vol
        al.alSourcef(self.source, al.AL_GAIN, vol)

    def _get_volume(self):
        return self._volume

#queue a sound buffer
    def add(self,sound):
        al.alSourceQueueBuffers(self.source, 1, sound.buf) #self.buf
        self.queue.append(sound)

#remove a sound from the queue (detach & unqueue to properly remove)
    def remove(self):
        if len(self.queue) > 0:
            al.alSourceUnqueueBuffers(self.source, 1, self.queue[0].buf) #self.buf
            al.alSourcei(self.source, al.AL_BUFFER, 0)
            self.queue.pop(0)

#play sound source
    def play(self):
        al.alSourcePlay(self.source)

#get current playing state
    def playing(self):
        al.alGetSourcei(self.source, al.AL_SOURCE_STATE, self.state)
        if self.state.value == al.AL_PLAYING:
            return True
        else:
            return False

#stop playing sound
    def stop(self):
        al.alSourceStop(self.source)

#rewind player
    def rewind(self):
        al.alSourceRewind(self.source)

#pause player
    def pause(self):
        al.alSourcePause(self.source)

#delete sound source
    def delete(self):
        al.alDeleteSources(1, self.source)

#Go straight to a set point in the sound file, uses 0.0-1.0 float value
    def seek(self,offset):
        al.alSourcei(self.source,al.AL_BYTE_OFFSET,int(self.queue[0].length * offset))

    rolloff = property(_get_rolloff, _set_rolloff,doc="""get/set rolloff factor""")
    volume = property(_get_volume, _set_volume,doc="""get/set volume""")
    pitch = property(_get_pitch, _set_pitch, doc="""get/set pitch""")
    loop = property(_get_loop, _set_loop, doc="""get/set loop state""")
    position = property(_get_position, _set_position,doc="""get/set position""")

game()

Be careful that what you're saying, Just a word Can break your personality!

Thumbs up

9

Okay, let's just say that you really don't see any errors here, which is quite unlikely, this might just have one reason which I actually encountered some time ago.
My laptop contained a really old graphics card from ATI, which is now AMD, and used a much older graphics driver than we're actually using today. It seemed that the SDL version pygame uses internally crashes when trying to access such old graphics cards, without any message. There wasn't a way to prevent this from inside the python app itself, that's why I tried my best and managed to compile some older version of pygame (it must have been 1.7.1 or 1.7.0) with a much older version of sdl and that worked for me on my old graphics card. But anyway, I'd recommend you to use the NVDA cursor to try and read the error messages inside the console, because I don't expect you to have such an old laptop, which is something around 8 or 9 years old now.
Best regards.
Hijacker

Thumbs up

10

Hi. No my graphic card is NVIDIA 920 MX.

Be careful that what you're saying, Just a word Can break your personality!

Thumbs up

11

Just to be clear, the extension scripts need to be copied over in to python/lib/site-packages/pyglet/media/drivers/openal. The python and Pyglet directory names may vary abit depending on versions, if pyglets installed as an egg file then open it as a zip file and copy the files into the relevant directory. After that you need to either have the OpenAL32.dll that comes with the example in your scripts directory or install OpenAL itself with OpenAOL soft.

If the script still isn't giving you any output, try putting print statements higher up the initialization chain and work your way down to see if you can get any results, for example:

import pygame
print 'pygame loaded'
import pygame.mixer
print 'mixer loaded'
from pyglet.media.drivers.openal import lib_openal as al
print 'al loaded'
from pyglet.media.drivers.openal import lib_alc as alc
print 'alc loaded'
pygame.init()
print 'pygame init'
etc.
-BrushTone v1.2.8: Accessible Paint Tool

Thumbs up