music does not play

0

I have the following code in python

#*-coding:utf-8;-*
import pygame
pygame.init()
pygame.mixer.music.load('ex1.mp3')
pygame.mixer.music.play()
pygame.event.wait()

In case, it should play a song when it is run in pycharm, however, it performs the function, waits a few seconds and simply terminates the program, without returning any errors, how can I fix this?

When using this way

#*-coding:utf-8;-*
from pygame import mixer
mixer.init()
mixer.music.load('ex1.mp3')
mixer.music.play()
import time
time.sleep(360)

The code ran normally, but I think that's not the best way to do this with python / pygame

    
asked by anonymous 01.04.2018 / 20:50

5 answers

2

Try this:

from pygame import mixer
mixer.init()
mixer.music.load('ex1.mp3')
mixer.music.play()
x = input('Digite algo para parar...')
    
01.04.2018 / 21:55
1

The issue is that calling pygame.event.wait() in almost all cases will return immediately: it returns any Pygame event - including mouse movement, etc ...

If you want to execute code in parallel with the music playing, simply write this code the call to pygame.mixer.music.play () starts the song asynchronously in parallel with its code Python.

If you use time.sleep, your Python code does nothing and the music is playing. The call to event.wait() returns, and the program exits - so the difference between your code. If you have a main loop of your application, waiting for keyboard events, doing things, etc ... this will work while the music plays.

(parallel tip: running the program inside pycharm is just a pycharm facility while it is being developed - it is important to understand that your program exists and can be called directly by the operating system.Python programs do not run " inside the pycharm ".)

    
02.04.2018 / 16:53
1
import pygame
pygame.mixer.init()
pygame.mixer.music.load('mu.mp3')
pygame.mixer.music.play()
x = input('Digite algo para parar a musica...')

Shortening the code

from pygame import mixer
mixer.init()
mixer.music.load('mu.mp3')
mixer.music.play()
x = input('Digite algo para parar a musica...')

Instead put the code the way you put it put it and it will work ... as Victor Antonio said, the call to event.wait() returns and the program quits ...

    
27.12.2018 / 11:54
0

The first method is not working because it should be pygame.mixer.init() instead of pygame.init()

    
06.12.2018 / 03:09
0

One option is to use a loopback next to the control if mixer.music is busy (get_busy method).

>

In the example I'm repeating the song until the i variable is greater than 5 .

from pygame import mixer
import time

mixer.init()
mixer.music.load('ex1.mp3')
mixer.music.play(-1)
i = 0
while (mixer.music.get_busy()):
  # Executa o que você quiser executar, no exemplo estou executando somente um sleep e um print
  # Fiz uma condição para quando o i > 5 parar de tocar a música e parar a execução por consequência
  time.sleep(1)
  if i > 5:
    mixer.music.stop()
    
10.01.2019 / 15:29