Last active
August 19, 2023 16:16
-
-
Save villares/2033198536a361179a9f8b11abe694dd to your computer and use it in GitHub Desktop.
Tocadores de arquivos mp3 com pygame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# TODO quando som termina, retomar não recomeça | |
# (mudar para próximo som autmaticamente?) | |
from pathlib import Path | |
import pygame | |
# Procura arquivos .mp3 na mesma pasta | |
folder = Path.cwd() # se quiser pode trocar por Path('/caminho/pasta/') | |
audio_files = [fp for fp in sorted(folder.iterdir()) | |
if fp.name.lower().endswith('.mp3')] | |
pygame.init() | |
screen = pygame.display.set_mode((800, 300)) | |
font = pygame.font.Font(None, 32) | |
# Mixer é a interface do pygame para audio | |
pygame.mixer.init() | |
current_audio = 0 # começa com o primeiro arquivo da lista | |
pygame.mixer.music.set_volume(0.7) # ajusta o volume | |
# Começa carregando o primeiro arquivo, começa a tocar e pausa | |
pygame.mixer.music.load(audio_files[current_audio]) | |
pygame.mixer.music.play() | |
pygame.mixer.music.pause() # opcional, se não quiser que já comece tocando | |
# Laço principal do pygame | |
running = True | |
while running: | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
running = False | |
elif event.type == pygame.KEYDOWN: | |
if event.key == pygame.K_p: # Pause o tocador | |
pygame.mixer.music.pause() | |
elif event.key == pygame.K_r: # Retoma o tocador | |
pygame.mixer.music.unpause() | |
elif event.key == pygame.K_s: | |
# muda qual arquivo vai tocar | |
current_audio = (current_audio + 1) % len(audio_files) | |
pygame.mixer.music.load(audio_files[current_audio]) | |
pygame.mixer.music.play() | |
elif event.key == pygame.K_t: | |
# Retoma do começo a tocar o arquivo | |
pygame.mixer.music.rewind() | |
pygame.mixer.music.play() | |
elif event.key == pygame.K_e: | |
# Encerra o tocador | |
pygame.mixer.music.stop() | |
running = False | |
elif pygame.K_0 <= event.key <= pygame.K_9: | |
# checa se foram apertadas teclas de número | |
numero = event.key - pygame.K_0 | |
if numero <= len(audio_files) - 1: | |
current_audio = numero | |
pygame.mixer.music.load(audio_files[numero]) | |
pygame.mixer.music.play() | |
# Parte que desenha na tela | |
screen.fill((0, 0, 0)) # fundo preto, limpa a tela | |
if pygame.mixer.music.get_busy(): | |
status = 'Tocando' | |
else: | |
status = 'Parado' | |
instructions = [ | |
f'{status}: {audio_files[current_audio].name}', | |
'Tecle:', | |
'"p" para pausar', | |
'"r" para retomar', | |
'"s" para seguir para outro arquivo', | |
'"t" para tocar do começo', | |
'"e" para encerrar', | |
'Números de 0 a 9 para os 10 primeiros arquivos.', | |
] | |
y = 10 | |
for line in instructions: | |
text = font.render(line, True, (255, 255, 255)) | |
screen.blit(text, (10, y)) | |
y += 30 | |
# atualiza a tela | |
pygame.display.flip() | |
# Encerra tudo (fecha a janela) | |
pygame.quit() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Procura arquivos mp3 na pasta corrente e toca enquanto uma tecla é pressionada. | |
A tecla que dispara o som é o primeiro caractere do nome do arquivo, ou | |
código entre colchetes de constante K_... do pygame, exemplo: | |
a-mar.mp3 (tecla A) | |
1-vento.mp3 (tecla 1) | |
[LEFT]-zumbido.mp3 (seta para esquerda) | |
[SPACE]-chuva.mp3 (barra de epaço) | |
""" | |
from pathlib import Path | |
import pygame | |
folder = Path.cwd() # se quiser pode trocar por Path('/caminho/pasta/') | |
key_to_files = {} | |
for fp in sorted(folder.iterdir()): | |
if not fp.name.lower().endswith('.mp3'): | |
continue # pula arquivos que não terminam em .mp3 | |
if fp.name[0] == '[': # nomes com código entre colchetes | |
c = fp.name[1:fp.name.find(']')] | |
else: # outras teclas | |
c = fp.name[0].lower() | |
key_code = getattr(pygame, 'K_' + c, None) # procura constante do pygame | |
if not key_code: # tecla ou código entre colchetes não serve | |
print(f'Nome incompatível: {fp.name}') | |
continue | |
key_to_files[key_code] = fp # põe constante e path do arquivo no dict | |
pygame.init() | |
# tela de 800 x 200 pixels | |
screen = pygame.display.set_mode((800, 800)) | |
font = pygame.font.Font(None, 24) | |
# Mixer é a interface do pygame para audio | |
pygame.mixer.init() | |
pygame.mixer.music.set_volume(0.7) # ajusta o volume | |
# Laço principal do pygame | |
running = True | |
play_file = None | |
while running: | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
running = False | |
elif event.type == pygame.KEYDOWN: | |
play_file = key_to_files.get(event.key) | |
if play_file: | |
pygame.mixer.music.load(play_file) | |
pygame.mixer.music.play() | |
elif event.type == pygame.KEYUP: | |
pygame.mixer.music.fadeout(200) | |
play_file = None | |
#pygame.mixer.music.stop() # meio brusco | |
# Parte que desenha na tela | |
screen.fill((0, 0, 0)) # fundo preto, limpa a tela | |
instructions = [ | |
'Aperte e segure uma tecla.', | |
'Disponíveis:'] + [fp.name for k, fp in key_to_files.items()] | |
if pygame.mixer.music.get_busy(): | |
instructions[0] = f'Tocando: {play_file.name if play_file else "Nenhum"}' | |
x = y = 10 | |
for line in instructions: | |
text = font.render(line, True, (255, 255, 255)) | |
screen.blit(text, (x, y)) | |
y += 30 | |
if y > screen.get_height(): | |
y = 70 | |
x += 250 | |
pygame.display.flip() # atualiza a tela | |
# Encerra tudo (fecha a janela) | |
pygame.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Para usar, sugiro installar o Thonny IDE que já vem com Python https://thonny.org
no menu tools/ferramentes > manage packages/gerenciador de pacotes...
procurar e installar pygame.