2

I am manipulating sound files in python using pygame module. It works OK from withing interactive python session, but the same code produces nothing from bash:

interactive python

$ sudo python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> from pygame import mixer
>>> mixer.init()
>>> mixer.music.load('zho1ngguo2.mp3')
>>> mixer.music.play()

==> sound played

But nothing happens from bash:

$ cat  playmp3.py
import pygame
from pygame import mixer
mixer.init()
mixer.music.load('zho1ngguo2.mp3')
mixer.music.play()

$ sudo python  playmp3.py

==> No sound

Any ideas?

AJN
  • 1,196
  • 2
  • 19
  • 47
  • 2
    Why are you using sudo to run python? – PM 2Ring Nov 29 '14 at 14:13
  • otherwise certain modules are not recognized: "ImportError: No module named pygame" – AJN Nov 29 '14 at 14:18
  • 1
    You should not have to run Python as root; I suspect you probably installed the pygame library in the root's homedir, or some such. If you install is system-wide, *any* user can use it. – Martin Tournoij Nov 30 '14 at 00:02
  • 2
    Yes Carpetsmoker, unfortunately many libraries are available only with sudo. I don't know what is causing this, I use sudo only when required. I should probably ask for this issue in a separate question. – AJN Nov 30 '14 at 00:15

1 Answers1

3

mixer.music.play() only starts the playback, it doesn't stop python from exiting (and thereby ending playback) immediately. You have to wait until the song is over. The most straightforward way to do this is to tell mixer.music to send you an event when playback ends and wait for it:

import pygame
from pygame import mixer

# to use the event queue, this is required.
pygame.init()

mixer.init()

# or some other event id. This just has to be the same here and below.
mixer.music.set_endevent(pygame.USEREVENT + 1)
mixer.music.load('foo.mp3')
mixer.music.play()

ev = 0

while ev != pygame.USEREVENT + 1:
  ev = pygame.event.wait()
Wintermute
  • 42,983
  • 5
  • 77
  • 80