0

I've got two mp3 files that are exactly the same length, and line up pretty well musically. The intended effect is that, when a button is pressed, the song playing switches from one song to the other. My implementation looks like this:

import pygame
import sys
framerate = 30
from mutagen.mp3 import MP3
audio = MP3("foo.mp3")
songleng = audio.info.length*1000
songpos = 0
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.init()
clock = pygame.time.Clock()
size = [10, 10]
screen = pygame.display.set_mode(size)
char = 'foo'
pygame.mixer.music.load('foo.mp3')
pygame.mixer.music.play(-1)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                songpos += pygame.mixer.music.get_pos()%songleng
                pygame.mixer.music.stop()
                print(songpos)
                if char == 'bar':
                    pygame.mixer.music.load('foo.mp3')
                    char = 'foo'
                else:
                    pygame.mixer.music.load('bar.mp3')
                    char = 'bar'
                try:
                    pygame.mixer.music.play(-1, songpos/1000)
                except Exception as e:
                    print(str(e))
                print(pygame.mixer.music.get_pos())
        pygame.display.flip()
        clock.tick(framerate)

Now, while this does seem to work some of the time, sometimes the audio gets very watery, and sometimes the whole thing just hangs, not responding to keyboard interrupt. Very rarely, I get a segmentation fault. Pdb gives me a different error every time. I've tried rounding songpos, which doesn't seem to help, and I've tried calling pygame.mixer.music.set_pos(), which has the same effects. I should also mention that the mp3 frequency, 44100, is correct.

I haven't tried it on any other computers, so if this works on your system that'll be the first step to figuring out the problem. I've got a pretty clean install of Ubuntu 16.04.3.

  • 1
    The whole thing hangs because your clock.tick and display.flip are accidentally nested inside your event loop. – Blake O'Hare Feb 01 '18 at 08:23
  • @BlakeO'Hare You're right that I made this mistake, but the same problems occur when clock.tick and display.flip are indented properly, or when they aren't present at all. – TheCakeFlavor Feb 02 '18 at 09:30
  • Sorry, I don't have any definitive answers for you, but saw that that might be a problem. Once you fixed that, another thing you may want to just try is converting the files to ogg. PyGame historically has some flakey issues with mp3 playback. – Blake O'Hare Feb 02 '18 at 09:34
  • @BlakeO'Hare ogg works much better. Maybe I'll leave this question up anyway, for posterity. – TheCakeFlavor Feb 02 '18 at 21:48

0 Answers0