7

Ok, this is what I got:

import pygame
import sys

from pygame.locals import *

bif="bg.jpg"
mif="pkmn.png"
sif="bubble.png"
song_1="testaudio.mid"

pygame.init()

FPS = 30  # FPS
FPSCLOCK = pygame.time.Clock()  # FPS

screen = pygame.display.set_mode ((600,375),0,32)

intro=pygame.mixer.Sound(song_1)
intro.play()

background = pygame.image.load(bif).convert()

pygame.mouse.set_visible(0)

char = pygame.image.load(mif).convert_alpha()
x = screen.get_width()/2 - char.get_width()/2
y = screen.get_height() - char.get_height()

bubble = pygame.image.load(sif).convert_alpha()
shoot_y = 0

move_speed = 15  # FPS

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pressed = pygame.key.get_pressed()
    if pressed[K_LEFT]:
        x -= move_speed
    if pressed[K_RIGHT]:
        x += move_speed
    if pressed[K_UP]:
        y -= move_speed
    if pressed[K_DOWN]:
        y += move_speed

    if event.type==KEYDOWN:
        if event.key==K_SPACE:
            shoot_y = y
            shoot_x = x

    screen.blit(background,(0,0))

    if shoot_y > 0:
        screen.blit(bubble,(shoot_x, shoot_y))
        shoot_y -= 10


    screen.blit(char,(x,y))

    pygame.display.update()
    FPSCLOCK.tick(FPS)  # FPS

So I got some midi files I created, however I keep getting "Unable to open file 'testaudio.mid", I tried quite a bit but I'm really confused, I'm new to pygame but can't figure this out, I've looked everywhere but still can't get it to work, even in this same site but still couldn't figure it out.

I really hope someone can help me by modifying my code or showing me the way to some clearer example cause I've been unable to understand the one I found.

Thanks (:

Bob Lozano
  • 838
  • 2
  • 13
  • 38

3 Answers3

12

The following code will play music.mid located in the current directory

import pygame
pygame.init()

pygame.mixer.music.load("music.mid")
pygame.mixer.music.play()
Adrian G
  • 775
  • 6
  • 11
7

If you have a simple program that exits after the play instruction, music playback will stop.

you should add the following two lines:

while pygame.mixer.music.get_busy():
    pygame.time.wait(1000)

to prevent the program from exiting before the music has finished playing.

RufusVS
  • 4,008
  • 3
  • 29
  • 40
-1

Following from the above answer , rather than waiting for 1000 you can find the length of the midi file using

length = pygame.time.get_ticks()

and then set the waiting time to length

staplegun
  • 79
  • 10
  • 1
    I think you are talking about my answer, which is currently below, not above, yours. And I checked the docs, and `pygame.time.get_tics()` only gets the number of ticks elapsed since pygame was initted, not the length of a midi file. – RufusVS Jul 14 '21 at 13:58