music problems when using pygame + multiprocessing

2019-06-06 05:07发布

I'm tring to run a script that would play music via a process. the code below is a stripped down version of my code but it's good enough to replicate the problem. If I call the normal() procedure I hear music so I know the procedure is correct and everything is connected properly, however, if I call normal() using multiprocessing there is no sound... It runs normal() but still no audio...

Any suggestions? thanks!

#!/usr/bin/python
# 
# Import required Python libraries
import pygame, time
import multiprocessing as mp
localtime = time.asctime( time.localtime(time.time()) )
pygame.init()
cs = 0 

def normal( cs ):
# main loop
    try:
        if cs == 1: 
              while cs == 1:
                 print " Starting normal function"   
                 pygame.mixer.music.load('/home/user/scripts/music.mp3')
                 pygame.mixer.music.play()
                 time.sleep(20)
                 pygame.mixer.music.stop()              
              #return;

    except KeyboardInterrupt:
        print "Quit" 

try:

  print " Starting music"   
  # play here 
  cs = 1
  p2 = mp.Process(target=normal, args=(cs,))
  p2.start()
  p2.terminate()
 #normal( cs )           

except KeyboardInterrupt:
  print "  Quit" 
# End script    

1条回答
家丑人穷心不美
2楼-- · 2019-06-06 05:53

Try this:

pygame.mixer.music.load('/home/user/scripts/music.mp3')
pygame.mixer.music.play(-1,0) # add this args
sleep(20) #remove this line
mixer.music.stop() #remove this line

Adding pygame.mixer.music.play(-1,0) means that the music will play in loop until you quit the game e.g.

Try to remove sleep(20) and mixer.music.stop().

Also check if you are playing a 44.1kHz MP3, the default 22050 frequency works, but a 48kHz mp3 plays in less than half speed - 48000 or 24000 works then.

Or try this approach depending on sample rate:

pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
sound = pygame.mixer.Sound('/home/user/scripts/music.mp3').play()

Or try this.

查看更多
登录 后发表回答