0

I'm trying to get some music using mixer to pause a song, but I always get the error above. I'm in VS Code, there is no extra file named 'pygame.py', and the mixer works just fine.

Music_List = os.chdir(r'Ene\\Music')
Music_Loader = random.choice((os.listdir(Music_List)))
mixer.music.load(Music_Loader)
print("Now playing: " + Music_Loader)
mixer.music.play()
while pygame.mixer.music.get_busy():
    pygame.mixer.music.get_pos()
    for event in pygame.event.get():
        if event.type == pygame.K_SPACE:
            pygame.mixer.pause
pygame.mixer.music.fadeout(20)
mixer.music.stop()

EDIT: using if event.key == pygame.key.K_SPACE: works, but now an error saying "video system not initalized" comes up".

CodeBabylon
  • 51
  • 1
  • 7

3 Answers3

1

event.type has only 2 values KEYUP and KEYDOWN. This is why you see this error as event.type does not have K_SPACE. Use if event.key == pygame.K_SPACE: and you won't get this error.

Gary
  • 909
  • 8
  • 20
0

This is a working version, it looks like this should be what you are looking for.

import os,pygame,random,sys,pygame.locals as pl
pygame.init() # step 1 to fix the error, initialize (most) pygame modules
pygame.mixer.init() # inizialize the mixer
Music_List = os.chdir(r'C:\\PATH\\TO\\MUSIC\\FILE.mp3')
Music_Loader = random.choice((os.listdir(Music_List)))
pygame.mixer.music.load(Music_Loader)
print("Now playing: " + Music_Loader)
pygame.mixer.music.play()
display = pygame.display.set_mode((200,100)) # step 2 to fix the error
while pygame.mixer.music.get_busy():
    pygame.mixer.music.get_pos()
    for event in pygame.event.get():
        if event.type == pl.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pl.KEYDOWN:
            if event.key == pl.K_SPACE:
                pygame.mixer.music.pause() # to stop it, you need to use "mixer.music.pause()"

pygame.mixer.music.fadeout(20)
pygame.mixer.music.stop()

The reason why this error pops up is that pygame needs a display setup to work. I do not now a way how not to do it like this.

And actually, there are more event-types than only "KEYDOWN" and "KEYUP". For example: "MOUSEBUTTONUP","VIDEORESIZE" and some more. https://www.pygame.org/docs/ref/event.html

Twistios_Player
  • 120
  • 3
  • 11
  • pygame.init() doesn't work, VS Code says there's no module for it. – CodeBabylon Nov 13 '19 at 23:54
  • I had to make some adjustments to the code (otherwise I would get errors in VS Code), and now I get an error saying "'Event' object has no attribute 'key'" – CodeBabylon Nov 14 '19 at 04:23
  • 1.: Posibility: Your statement is not correctly intended. "event.key" needs to be one level more right than "event.type". 2. Posibility: Not every type has a key argument. For example pl.MOUSEBUTTONDOWN uses "event.button". – Twistios_Player Nov 16 '19 at 15:21
0

You need to initialize pygame using pygame.init(). Heres an example:

import pygame
pygame.init()

rest of your code
Joe The Bro
  • 105
  • 1
  • 8