1

I'm currently writing a basic music player (no GUI). I'm trying to find a way to pause the music at any point in the song I'm playing, and skip at any point as well. I've tried keyboard and opencv modules, but there is a small delay, and you have to press at the right time to pause. Is there any way around this? Or is there another module I've missed? I've isolated actual playing of the song in a function, and here it is:

from pygame import mixer
def playsong(songname):
    global songs, filepath
    print('Currently playing: '+songname)
    print('Press \'n\' to skip\nand \'p\' to pause and unpause')
    mixer.init()  # initiate the mixer instance
    mixer.music.load(filepath + songname + '.mp3')
    mixer.music.play()  # plays the music

My current code to pause and skip the music is:

while mixer.music.get_busy():
    if keyboard.is_pressed('n'):
        mixer.music.stop()
        break
    if keyboard.is_pressed('p'):
        mixer.music.pause()
       
Axe319
  • 4,255
  • 3
  • 15
  • 31
  • Have you tried pygame's input system? `while mixer.music.get_busy(): keys = pygame.key.get_pressed() # Pause playback if keys[pygame.K_p]: mixer.music.pause()` – Resistnz Oct 10 '20 at 11:14
  • You may also want to try a while loop that is always running, then use an if statement to check mixer.music.get_busy(), just in case this is the source of the input lag. – Resistnz Oct 10 '20 at 11:41
  • I tried the pygame suggestion, but that forces me to initialize the pygame module using 'pygame.init()'. That stops the music being played, unfourtunately. As for the input lag using it as an if statement does help, but only very little. The input lag is still noticeable. Thank you for your help though, gives me a lot more I can look at! –  Oct 10 '20 at 11:57
  • Ok fair enough with pygame, modules like keyboard should be fast enough without much lag. One last thing, have you tried not even checking mixer.music.get_busy(), and just pausing when a key is pressed? I know that it will create issues later when the music is stopped etc., but it may help narrow down the latency problem. If that doesn't work, I'm not sure what will. Thanks for taking my suggestions! :) – Resistnz Oct 10 '20 at 12:34
  • This seems more a problem with the keyboard input than PyGame, maybe this answer on single-key-input will help: https://stackoverflow.com/questions/510357/how-to-read-a-single-character-from-the-user – Kingsley Oct 11 '20 at 21:52

0 Answers0