A small MIDI visualizer, written in C++/OpenGL.
Binaries for Windows, macOS and Ubuntu (experimental) are available in the Releases tab.
See the troubleshooting section if you encounter any issue.
[image: Result image]
Usage
On Windows and macOS platforms, you can now run the application by simply double-clicking on it. You will then be able to select a MIDI file to load. A Settings panel allows you to modify display parameters such as color, scale, lines,... Images and videos of the track can be exported. Note that MIDIVisualizer is currently not able to play soundtracks, only display them.
Press p to play/pause the track, r to restart at the beginning of the track, and i to show/hide the Settings panel.
[image: Result image]
Command-line use
You can also run the executable from the command-line, specifying a midi file and display options. You can also trigger a video export directly from the command line. For instance:
--midi path to a MIDI file to load
--device name of a MIDI device to start a live session to (or VIRTUAL to act as a virtual device)
--config path to a configuration INI file
--size dimensions of the window (--size W H)
--position position of the window (--position X Y)
--fullscreen start in fullscreen (1 or 0 to enable/disable)
--gui-size GUI text and button scaling (number, default 1.0)
--transparency enable transparent window background if supported (1 or 0 to enable/disable)
--forbid-transparency prevent transparent window background(1 or 0 to enable/disable)
--help display a detailed help of all options
--version display the current version and build information
Export options
If you want to directly export a video/images, --export ... is mandatory. You can completely hide the application window using --hide-window.
code
--export path to the output video (or directory for PNG)
--format output format (values: PNG, MPEG2, MPEG4, PRORES)
--framerate number of frames per second to export (integer)
--bitrate target video bitrate in Mb (integer)
--postroll Postroll time after the track, in seconds (number, default 10.0)
--out-alpha use transparent output background, only for PNG and PRORES (1 or 0 to enable/disable)
--fix-premultiply cancel alpha premultiplication, only when out-alpha is enabled (1 or 0 to enable/disable)
--hide-window do not display the window (1 or 0 to enable/disable)
Configuration options
If display options are given, they will override those specified in the configuration file. Almost every option available in the GUI can be specified on the command line, refer to the detailed help for a complete list (./MIDIVisualizer --help). Options include:
code
--color-bg Background color (R G B in [0.0, 1.0])
--flashes-size Flash effect size (number in [0.100000,3.000000])
--particles-count Particles count (integer in [1,512])
--preroll Preroll time in seconds before starting to play (number)
--quality Rendering quality (values: LOW_RES, LOW, MEDIUM, HIGH, HIGH_RES) --show-keyboard Should the keyboard be shown (1 or 0 to enable/disable)
...
[image: Result image]
Troubleshooting
Please note that MIDIVisualizer requires OpenGL 3.2 or higher on all platforms.
MIDIVisualizer is not playing any sound.
MIDIVisualizer is only a MIDI viewer, and does not currently support audio playback.
I have encountered an issue while using MIDIVisualizer.
You can open an issue ticket here. Please also check the issue page, as some other people might have encountered a similar issue or offer help to your questions.
Windows
I can't open the application as it is blocked by Safeguard.
MIDIVisualizer is not generated with a Microsoft developer certificate, thus the warning. You can still run the application by allowing it in the Safeguard message panel.
I get an error message about a missing vcruntime140_1.dll.
This is a Windows component (part of the Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019) that is often updated, you should try installing the latest version from the Microsoft support website (vc_redistx64).
macOS
I can't open the application as it is considered unsafe.
MIDIVisualizer is not generated with an Apple developer certificate, thus the warning. You can still run the application by doing a right-click on it and selecting 'Open', this will mark the application as 'authorized' for future use.
Ubuntu
I can't run MIDIVisualizer by double-clicking it in the file manager.
This seems to be a limitation of the Nautilus file manager, you can either double-click the companion script, or create and register a .desktop file.
Compilation
The project is configured using Cmake. You can use the Cmake GUI ('source directory' is the root of this project, 'build directory' is build/, press 'Configure' then 'Generate', selecting the proper generator for your target platform and IDE); or the command line version, specifying your target generator.
Depending on the target you chose in Cmake, you will get either a Visual Studio solution, an Xcode workspace or a set of Makefiles. You can build the main executable using the MIDIVisualizersub-project/target. If you update the images or shaders in the resources directory, you will have to repackage them with the executable, by building the Packaging sub-project/target.
Dependencies
MIDIVisualizer depends on the GLFW3 library, the sr_gui library and RtMidi17, all included in the repository and built along with the main executable. It also optionally relies on FFMPEG v4.2 for video export. For licensing reasons only MPEG-2 and MPEG-4 exports are supported for now in the release builds.
On macOS and Windows, no additional dependencies are required. On Linux, you will need to have the following packages installed: xorg-dev libgtk-3-dev libnotify libasound2-dev, and if you plan on using FFMPEG, ffmpeg libavcodec-dev libavformat-dev libavdevice-dev.
Development
The main development steps were:
loading a MIDI file, and parsing the notes contained,
displaying a scrolling score with these notes,
adding visual effects to embellish the visualization,
maintaining the application and listening to user requests :)
It looks like you've shared the README and documentation for MIDI Visualizer, a standalone application that visualizes MIDI files graphically without playing sound. Here's a summary and highlights to help you get started or troubleshoot:
What is MIDI Visualizer?
A C++/OpenGL program that visualizes MIDI files.
Does not play audio; it only displays the MIDI notes graphically.
Supports Windows, macOS, and Ubuntu ("experimental").
Offers image and video export functionality.
Comes with settings and GUI to customize the visualization.
Basic Usage
Windows/macOS: Double-click the executable to open the GUI, select a MIDI file, and start visualizing.
Use p to Play/Pause visualization.
Use r to Restart track.
Use i to show/hide Settings panel.
Export images/videos of the visualization from the GUI.
Command-line Usage
You can run the program from the command line and specify files and export options, e.g.:
--format : Output format (PNG, MPEG2, MPEG4, PRORES).
--framerate : Frames per second when exporting video.
--bitrate: Video bitrate in Mbps.
--hide-window : Run without showing window (for non-interactive exports).
Overridable display options like background color, quality, flash size, etc.
Run ./MIDIVisualizer --help to see a full options list.
Troubleshooting
Common Notes:
OpenGL 3.2+ is required.
No sound output, this is visual only.
Windows
If blocked by Windows Defender SmartScreen (“Safeguard”), allow the executable manually.
Missing vcruntime140_1.dll means Visual C++ Redistributable is missing/corrupted — install from Microsoft.
macOS
App may be flagged as unsafe since it’s unsigned. Right-click → Open to bypass and mark as trusted.
User
oque?
Assistant
Oi! Parece que você enviou informações sobre um projeto chamado MIDI Visualizer, que é um programa para visualizar arquivos MIDI, mostrando as notas de forma gráfica, mas sem tocar o som.
Se você quiser, posso explicar melhor o que é, como usar, ou tirar dúvidas específicas. O que você precisa?
User
pode modificar o midi visualize?
Assistant
Sim! O MIDI Visualizer é um projeto open source escrito em C++/OpenGL, disponível no GitHub. Isso significa que você pode baixar o código-fonte, modificar conforme quiser, compilar e usar sua versão personalizada.
O que você precisa para modificar o MIDI Visualizer?
Conhecimentos básicos de C++ e OpenGL:
O projeto é feito em C++ com renderização por OpenGL.
Ambiente de desenvolvimento:
Você vai precisar de ferramentas como CMake, um compilador C++ (Visual Studio no Windows, Xcode no macOS, GCC/clang no Linux), e bibliotecas externas (que já estão incluídas no projeto).
Compilar o projeto:
Usar o CMake para configurar, gerar o projeto e compilar. O README explica como fazer isso em cada sistema.
Modificar o código:
Para mudar a forma como as notas são desenhadas, procure pelas partes do código que desenham os objetos ou que interpretam os dados MIDI.
Para adicionar efeitos visuais, pode editar shaders ou lógica de renderização.
Para modificar a interface gráfica, pode olhar a biblioteca sr_gui que é usada.
Posso te ajudar com:
Explicar como preparar o ambiente para compilar.
Orientar qual parte do código mexer para fazer determinada modificação (ex: mudar cores, layout, efeitos).
Ajudar com dúvidas sobre compilação e execução.
Se quiser, diga o que gostaria de modificar ou criar e te auxilio passo a passo!
User
pode fazer um parecido em python?
Assistant
Claro! Posso sim ajudar você a criar uma versão simples de um visualizador MIDI usando Python.
Como o MIDI Visualizer original é um app complexo em C++ com OpenGL, vamos criar uma versão básica para visualizar notas MIDI em uma janela gráfica usando bibliotecas Python.
Como fazer um visualizador MIDI simples em Python?
Visualizar graficamente: usando pygame, que é simples e boa para gráficos 2D
(Opcional) Usar pygame.midi para receber eventos MIDI ao vivo (mas aqui focaremos em arquivo)
Exemplo básico de visualizador MIDI em Python com Pygame
python
import mido
import pygame
import sys
# Configurações
WIDTH, HEIGHT = 800, 600
NOTE_HEIGHT = 10
SPEED = 0.5 # Quão rápido as notas se movem para cima
# Inicializar pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Visualizador MIDI simples")
# Carregar arquivo MIDI
midi_file = mido.MidiFile('exemplo.mid')
# Extrair eventos note_on com tempo absoluto
notes = []
time_elapsed = 0
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
# Guardar uma tupla: (tempo, nota)
notes.append((time_elapsed, msg.note))
# Função para converter nota MIDI (0-127) em posição Y na tela
def note_to_y(note):
# Mapear notas para uma faixa vertical (inverter eixo Y)
return HEIGHT - (note - 21) * (HEIGHT / 88) # 88 notas no piano
# Loop principal
clock = pygame.time.Clock()
start_ticks = pygame.time.get_ticks()
running = True
while running:
screen.fill((0, 0, 0)) # Fundo preto
# Tempo padrão (segundos) desde início da animação
current_time = (pygame.time.get_ticks() - start_ticks) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Desenhar notas que devem aparecer no tempo atual
for note_time, note in notes:
# Calcular posição vertical baseada no tempo (scroll up)
y = note_to_y(note) - (current_time - note_time) * 100 * SPEED
if 0 < y < HEIGHT:
# Desenhar um retângulo para a nota
pygame.draw.rect(screen, (0, 255, 0), (WIDTH/2, y, 100, NOTE_HEIGHT))
pygame.display.flip()
clock.tick(60) # 60 FPS
pygame.quit()
sys.exit()
User
precisa adicionar um piano com animação ao passar as notas
Assistant
Claro! Vou te ajudar a adicionar um teclado de piano animado na parte inferior da janela, que destaca as teclas sendo "tocadas" conforme as notas MIDI vão passando na visualização.
O que vamos fazer?
Desenhar o teclado (teclas brancas e pretas) na parte inferior.
Quando uma nota for ativada (note_on), vamos iluminar a tecla correspondente por um pequeno tempo.
Usar animação simples para destacar as teclas enquanto a nota está ativa.
Código completo atualizado com piano animado
python
User
precisa que as notas desçam como no synthesia
Assistant
Entendi! Você quer que as notas descresçam (desçam) verticalmente, como no Synthesia, em vez de subirem.
No código atual, as notas sobem porque a posição vertical é calculada subtraindo o tempo corrente do tempo da nota, multiplicado para o movimento.
Para inverter o sentido e fazer as notas descerem, basta mudar a fórmula de cálculo da posição vertical, fazendo as notas iniciarem no topo e descerem para o teclado na parte inferior.
Passo para inverter o movimento das notas (subir → descer):
Sendo que note_to_y_top é a coordenada Y inicial (topo da área) onde as notas começam a aparecer.
Exemplo modificado do trecho relevante no código completo
Vou fornecer a versão ajustada do código anterior para o movimento descendente das notas (como Synthesia):
python
User
precisa de sincronia e a notas estão descendo na horizontal não na vertical como o piano
Assistant
Entendi, você quer uma visualização estilo Synthesia clássico, onde:
As notas descem verticalmente em linhas verticais alinhadas com as teclas do piano.
A posição horizontal da nota corresponde exatamente à tecla do teclado (posição X).
A nota desce verticalmente do topo da tela para o teclado, que fica fixo na parte inferior.
As notas são sincronizadas no tempo, descendo com velocidade constante (ou controlada pelo tempo total do arquivo).
O teclado também destaca as teclas que estão sendo “tocadas”.
Implementação corrigida: notas descendo na vertical, alinhadas horizontalmente às teclas do piano
Veja abaixo um exemplo funcional e mais completo que implementa isso:
python
User
as notas estão subindo não descendo
Assistant
Obrigado pelo feedback! Vamos corrigir para garantir que as notas descem verticalmente da parte superior da tela em direção ao teclado posicionado na parte inferior, como no Synthesia.
Problema comum
Na fórmula que calcula a posição vertical y da nota, normalmente se faz algo assim para descida:
python
y = altura_da_tela - (tempo_corrente - tempo_nota) * velocidade
Mas se você colocou algo diferente, as notas podem subir ao invés de descer.
Código corrigido para notas DESCEREM da parte superior para o teclado
python
# NOTA IMPORTANTE:
# current_time - tempo em segundos desde o início do playback
# start - tempo em segundos de início da nota
# NOTE_SPEED - velocidade em pixels por segundo (quanto maior, mais rápido desce)
y = ( (current_time - start) * NOTE_SPEED ) - altura_da_nota
Mas para que as notas apareçam inicialmente acima da tela, e descendo tenha valor positivo para y, devemos definir a posição inicial da nota acima de 0, por exemplo y = - altura_da_nota quando current_time == start.
Assim a fórmula fica:
python
y = (current_time - start) * NOTE_SPEED - altura_da_nota
E no desenho você desenha as notas na posição y (vertical).
Quando y chega próximo do teclado (que está no fundo da tela, por exemplo HEIGHT - PIANO_HEIGHT), as notas estão chegando ao fim.
Para te ajudar, aqui está a parte relevante já corrigida do código para a descida vertical das notas alinhadas ao piano (trecho da lógica de desenho das notas):
python
# dentro do loop principal, ao desenhar cada nota:
t = current_time - start # tempo passado desde que a nota começou
# altura do retângulo que representa a nota, proporcional à duração da nota
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration * NOTE_SPEED))
# Posição vertical da nota = distância descendente desde acima da tela
y = t * NOTE_SPEED - h
if 0 <= y <= HEIGHT - PIANO_HEIGHT: # só desenhar se estiver dentro da área visível
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
User
Se quiser, posso ajudar a:
Ajustar velocidade baseada no BPM real do MIDI
Mostrar o progresso da música
Controlar pausar/reiniciar
Outras melhorias visuais
Assistant
Legal! Vou te ajudar a implementar essas funcionalidades básicas no visualizador MIDI em Python:
1) Ajustar velocidade baseada no BPM real do MIDI
O arquivo MIDI geralmente traz o BPM (tempo) via eventos set_tempo, que indicam microsegundos por batida.
Podemos extrair o BPM e definir a velocidade das notas para que elas desçam "na velocidade certa", isto é, fechando o tempo visual com o tempo real da música.
Como calcular:
O evento set_tempo indica quantos microssegundos tem um quarto de nota (uma batida).
BPM = 60.000.000 / microsegundos_por_batida
Vamos buscar o primeiro evento set_tempo e extrair o BPM.
2) Mostrar o progresso da música
Pode ser um simples desenho (barra) na parte superior com a porcentagem do progresso do arquivo MIDI baseado no tempo atual e no tempo total.
3) Controlar pausar/reiniciar com teclas
Por exemplo:
Barra de espaço: pausar / continuar
Tecla r: reiniciar
Código atualizado com essas funcionalidades básicas:
python
User
precisa de sincronia das notas, o mesmo andamento do midi com as notas chegando ao piano
Assistant
Entendi! Você precisa que a visualização esteja sincronizada exatamente com o andamento do MIDI, ou seja, que as notas demorem o tempo certo para descerem do topo da tela até o teclado, chegando exatamente quando deveriam "tocar" no ritmo da música de acordo com o BPM.
Como garantir sincronia tempo ↔ posição das notas?
Conceito chave:
As notas começam a aparecer antes do momento que seu som deve tocar, a uma distância/tempo fixo de “antecedência” chamado preroll ou lead time.
Ou seja, a nota demora um certo tempo preroll descendo até o teclado, chegando exatamente no momento certo para o usuário.
( t_{\text{nota}} ) = tempo em que a nota começa no MIDI (em segundos)
preroll = quanto tempo em segundos antes da nota tocar que ela aparece no topo (dá o tempo para a nota descer)
área_visível = altura total da área para a animação (por exemplo, do topo da janela até o teclado)
Esta fórmula posiciona a nota no topo da área para ( t = t_{\text{nota}} - \text{preroll} ), movimentando para baixo até chegar em Y=0 no momento ( t = t_{\text{nota}} ).
Notas para ( t_{\text{actual}} < t_{\text{nota}} - \text{preroll} ) não aparecem, e notas com ( t_{\text{actual}} > t_{\text{nota}} ) já devem estar no teclado (ou desaparecer).
Implementação prática no código
Passo 1: Definir o tempo de preroll (por exemplo 3 segundos, ou ajuste que quiser)
python
PREROLL = 3.0 # segundos de antecedência para as notas descerem
Passo 2: Calcular posição Y (vertical) da nota no loop de desenho no tempo:
python
time_since_appear = current_time - (start - PREROLL)
if 0 <= time_since_appear <= PREROLL:
# Posição Y proporcional ao tempo decorrido do preroll
y = ( (time_since_appear / PREROLL) * área_visível_altura )
else:
# Nota fora da tela ou não apareceu ainda
continue
User
Ajustar o valor do preroll para ficar confortável visualmente
Fazer o cálculo dinâmico da velocidade baseado no BPM e compasso e a nota quando a ponta do retangulo parecer encostar na tecla ter a animação para mais sincronia
Assistant
Perfeito! Vamos melhorar o visualizador para que:
O preroll (tempo que a nota “viaja” caindo antes de tocar) seja ajustável para ficar confortável.
A velocidade de descida das notas seja calculada dinamicamente com base no BPM do MIDI.
A posição vertical da nota seja calculada para que a ponta da nota (final do retângulo) toque exatamente a tecla no momento correto da nota.
Tenha uma pequena animação para sincronia visual quando a nota "encosta" na tecla (ex.: um pequeno “flash” ou mudança rápida).
1) Ajustando preroll e velocidade dinamicamente
O preroll será dado em segundos (ex: 3 segundos).
A nota descerá do topo assistido pelo preroll.
Para garantir que a ponta do retângulo encoste exatamente na tecla no tempo de início da nota, calculamos a velocidade como:
A área visível é do topo até a base do teclado, então a nota, que tem uma altura certa, precisa ser desenhada de forma que o fundo (y + h) alcance o teclado exatamente na marcação de tempo.
2) Implementação da posição vertical com sincronização ponta da nota → tecla
python
# y é a posição do topo do retângulo da nota
# h é a altura do retângulo (proporcional a duração)
# Queremos que topo nesta fórmula:
# Na hora t = start (tempo da nota), y + h = altura do teclado (posição do teclado)
# Quando nota aparece (t = start - preroll), y = 0 (topo da área)
Assim a nota começa no topo e desce, e a ponta dela alcança o teclado exatamente no tempo start.
3) Animação visual de “toque” quando a nota chega ao teclado
Podemos fazer um efeito simples, por exemplo:
Quando a nota está tocando (entre start e start + duração), a tecla do piano recebe uma animação de brilho que dura ANIM_DURATION segundos.
Podemos usar uma variável de tempo para controlar a intensidade desse brilho (fade in / fade out ou um pulso rápido).
User
precisa adicionar controle de velocidade das notas e opção para colocar um video como background aparecendo junto com as notas e o efeito do piano
Assistant
Ótimo! Para adicionar controle dinâmico da velocidade das notas e a opção de um vídeo como background atrás das notas e do piano, temos duas partes principais:
1) Controle dinâmico da velocidade das notas
Vamos adicionar no script:
Uma variável speed_multiplier para controlar a velocidade da queda das notas.
Ajustar o cálculo da velocidade para multiplicar por essa variável.
Mapear teclas para aumentar/diminuir essa velocidade em tempo real (ex: < e > ou + e -).
2) Vídeo como background no Pygame
Para exibir vídeo no Pygame, podemos usar o pacote opencv-python (cv2) para ler frames do vídeo e renderizá-los como textura a cada loop do Pygame.
Instalação
bash
pip install opencv-python
Como funciona na prática
Abrir o vídeo com OpenCV.
No loop, ler frame, converter para superfície Pygame e desenhar atrás dos elementos.
Ajustar o vídeo para caber na tela.
Se o vídeo acabar, reiniciar ou parar.
Código adaptado com controle de velocidade + background de vídeo
Vou mostrar um exemplo simplificado das partes principais que você pode juntar ao código anterior:
python
User
precisa de as notas e o piano passando no foreground quanto o video no background
Assistant
Claro! Para fazer isso corretamente em Pygame, o vídeo deve ser desenhado no background, ou seja, primeiro você desenha o frame do vídeo, e depois desenha as notas + piano por cima, formando o foreground.
Seguindo o seu pedido:
Vídeo no background: Renderizado primeiro.
Notas e piano no foreground: Renderizados depois, sobre o vídeo.
Como fazer isso no código
Imagine a ordem no seu loop principal:
python
# 1. Desenhar vídeo no background
screen.blit(video_frame_surface, (0, 0))
# 2. Desenhar as notas descendo
desenhar_notas()
# 3. Desenhar o piano fixo na parte inferior
desenhar_piano()
Exemplo simplificado de estrutura do loop principal:
python
while running:
# Ler eventos e controles
# Obter frame do vídeo e desenhar no fundo
video_frame = get_video_frame() # retorna pygame.Surface com frame atual do vídeo
screen.blit(video_frame, (0, 0))
# Desenhar as notas (retângulos verdes, por exemplo)
for nota in notas_ativas:
pygame.draw.rect(screen, cor, (x, y, w, h))
# Desenhar o teclado por cima do vídeo e notas
draw_piano(teclas_ativas)
# Finalmente atualizar o display
pygame.display.flip()
Por que essa ordem é importante?
No Pygame (e na maioria das APIs gráficas 2D tradicionais), as chamadas de desenho são em ordem; o último objeto desenhado fica "por cima".
Se desenhar vídeo por último, ele cobrirá tudo, você só verá o vídeo.
Se desenhar vídeo primeiro, depois as notas, depois o piano, o resultado é:
Vídeo — atrás Notas — meio Piano — na frente
Atenção ao fundo transparente e outros efeitos
Se você quiser que o fundo do piano seja transparente para deixar o vídeo aparecer através dele, tem que usar ferramentas avançadas (ex: usar imagens PNG com canal alfa, ou shaders com OpenGL).
No Pygame padrão, você pode criar uma superfície para o piano com transparência e usar convert_alpha() para mesclar.
Recapitulando passo a passo em seu código:
Inicialize OpenCV para carregar vídeo.
No loop Pygame, leia um frame do vídeo e converta em superfície Pygame.
Limpe a tela com o frame do vídeo (blit).
Desenhe as notas (retângulos etc).
Desenhe o teclado piano.
Atualize a tela.
Posso ajudar enviando uma versão completa, pronta para rodar? Com comentários e essas etapas claras?
Quer que eu faça isso?
User
sim
Assistant
Perfeito! Vou te passar um exemplo completo em Python que:
Lê um arquivo MIDI e exibe as notas descendo sincronizadas (com preroll e controle de velocidade).
Desenha um piano na parte inferior com animação nas teclas tocadas.
Usa um vídeo (via OpenCV) como background.
Desenha as notas e piano no foreground, sobre o vídeo.
Permite controle de velocidade das notas com + e -.
Para adaptar a resolução do vídeo ao tamanho da janela do Pygame (800x600 no exemplo), o código já usa:
python
frame = cv2.resize(frame, (WIDTH, HEIGHT))
Isso redimensiona o frame capturado para isso.
Mas algumas observações importantes para garantir boa qualidade e desempenho:
Redimensionamento dentro do loop
O redimensionamento ocorre para cada frame. Pode ser custoso para vídeos grandes, mas é necessário para ajustar ao tamanho da janela.
Manter proporção original do vídeo
Se quiser manter a proporção (sem deformar), é preciso calcular width e height compatíveis e adicionar barras pretas nas laterais (letterboxing/pillarboxing).
Exemplo de redimensionamento mantendo proporção com letterbox
Aqui está uma função para ajustar a resolução do vídeo mantendo a proporção, preenchendo com preto nas áreas sobrando:
No loop de eventos, capture o evento VIDEORESIZE para obter o novo tamanho:
python
for event in pygame.event.get():
if event.type == pygame.VIDEORESIZE:
WIDTH, HEIGHT = event.w, event.h
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
# Atualizar cálculos que dependem do tamanho da tela aqui
2) Atualizar elementos dependentes da resolução
Sempre que a janela for redimensionada, você precisa recalcular:
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = altura fixa do piano (você pode manter PIANO_HEIGHT fixo ou ajustar proporcionalmente)
black_key_width e black_key_height
visible_height = HEIGHT - white_key_height (área para notas)
Além disso, a função que redimensiona o vídeo deve receber o novo WIDTH e HEIGHT
3) Ajustar proporções na hora do desenho
No loop principal, use esses valores atualizados para:
Redimensionar o vídeo ao novo tamanho
Calcular posições e tamanhos de notas/piano dinamicamente com base em WIDTH e HEIGHT
Desenhar o piano fixo na parte inferior da nova janela
Ajustar a velocidade para descida proporcional à nova área visível
4) Exemplo resumido da adição do evento resize e recálculo
python
User
sim
Assistant
Claro! Aqui está o código completo atualizado para:
Janela redimensionável (pygame.RESIZABLE)
Ajustes dinâmicos das dimensões internas (teclas, área visível)
Redimensionamento do vídeo com letterbox adaptado à nova resolução
Notas descendo sincronizadas com preroll adaptadas à nova resolução
Piano animado fixo na parte inferior
Controle de velocidade, pausa e reinício mantidos
python
User
precisa de adicionar mais controle da reprodução do video ( background )
Assistant
Claro! Para adicionar mais controle sobre a reprodução do vídeo de fundo do seu visualizador MIDI em Pygame, você pode implementar recursos como:
Pausar e retomar o vídeo junto com a visualização (sincronizar pausa).
Ajustar a velocidade/reproduzir em slow motion.
Reposicionar (seek) o vídeo.
Reiniciar o vídeo junto com a música.
Vou te mostrar como integrar esses controles de forma simples no código que você já tem.
Passos para controle básico do vídeo
1) Pausar e retomar o vídeo
Para isso, no momento que a visualização for pausada, você não deve avançar no vídeo. Então a função get_video_frame() precisa respeitar esse estado e não ler frame novo enquanto o vídeo está "pausado".
2) Controlar velocidade do vídeo
Semelhante às notas, podemos controlar uma variável video_speed que define quantos frames avançar por atualização.
Exemplo inicial sem decodificação avançada pode ser aproximado pulando frames.
Código exemplo para integração no seu loop principal
Variáveis novas
python
video_paused = False
video_speed = 1.0 # 1.0 = normal, 0.5 = metade da velocidade
video_frame_time_accum = 0.0
video_fps = cap.get(cv2.CAP_PROP_FPS) or 30 # tentar detectar fps do vídeo
Função para obter frames do vídeo respeitando velocidade e pausa
python
def get_video_frame_controlled(delta_time):
global video_frame_time_accum, video_paused
if video_paused:
# não avança frame
return current_video_surface # variavel global com último frame
video_frame_time_accum += delta_time * video_speed
frames_to_advance = int(video_frame_time_accum * video_fps)
if frames_to_advance >= 1:
video_frame_time_accum -= frames_to_advance / video_fps
# pular frames_to_advance - 1 frames para acompanhar speed
for _ in range(frames_to_advance - 1):
ret = cap.grab() # pular frame
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = resize_with_letterbox(frame, WIDTH, HEIGHT)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
surf = pygame.surfarray.make_surface(frame)
return surf
else:
# manter frame antigo
return current_video_surface
User
sim
Assistant
Claro! Aqui está o código completo atualizado para seu visualizador MIDI com vídeo background, agora com controle aprimorado da reprodução do vídeo:
Pausar e retomar o vídeo junto com a visualização (tecla space)
Notas descendo sincronizadas e piano animado no foreground
Controle da velocidade das notas (+ e -)
python
User
precisa de as notas ser as que estão no midi, porque está tocando notas que não estão neste midi em questão tambem
Assistant
Esse comportamento (notas aparecendo que não estão no arquivo MIDI) geralmente acontece quando as notas extrapolam o intervalo padrão do piano desenhado, ou quando o cálculo da posição horizontal tenta processar notas fora do intervalo gerenciado.
No seu caso, o visualizador atualmente assume sempre o piano padrão de 88 teclas musicais do A0 (midi 21) até o C8 (midi 108). Se seu arquivo MIDI contém notas fora deste intervalo, o código não está filtrando estas notas, logo elas aparecem, mas sem nenhuma alocação correta no piano.
Além disso, se o cálculo horizontal não protege contra notas fora do range, pode desenhar em posições erradas, criando "notas fantasmas".
Passos para corrigir:
1) Filtrar notas que estão fora do intervalo MIDI visualizado
No momento de processar as notas (antes de armazenar na lista notes), descarte notas menores que 21 e maiores que 108.
Exemplo:
python
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
if 21 <= msg.note <= 108: # <-- Filtra aqui
note_on_times[msg.note] = time_elapsed
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times:
if 21 <= msg.note <= 108: # <-- E aqui
start = note_on_times[msg.note]
duration = time_elapsed - start
notes.append((start, msg.note, duration))
del note_on_times[msg.note]
2) Ao desenhar, tenha também cuidado para não tentar desenhar notas fora do range
Antes de calcular a posição no teclado:
python
if note < FIRST_MIDI_NOTE or note > FIRST_MIDI_NOTE + NUM_KEYS - 1:
continue # descartar notas fora do piano
3) Para garantir consistência, publique uma variável que defina o intervalo das notas visíveis
python
MIN_VISIBLE_NOTE = 21
MAX_VISIBLE_NOTE = 108
User
sim
Assistant
Claro! Aqui está o código completo atualizado com as correções para que somente as notas MIDI dentro do intervalo do piano (21 a 108) sejam consideradas e desenhadas.
python
User
precisa de que as notas sejam as mesmas do midi neste caso tem um acorde de do maior com as notas do, mi e sol, este codigo esta tocando notas formando outro acorde não o de do que contem no midi
Assistant
Se o seu visualizador está mostrando notas que não correspondem exatamente às notas presentes no seu arquivo MIDI (exemplo: está tocando notas extras que não fazem parte do acorde de Dó maior que tem apenas Dó, Mi e Sol), provavelmente o problema está na forma como o código está interpretando as mensagens MIDI, especialmente quando há múltiplos canais, programas, ou notas legadas.
Aqui estão algumas causas comuns e como corrigir para que as notas exibidas correspondam exatamente às notas no arquivo MIDI:
Possíveis causas e soluções
1) Eventos note_off substituídos por note_on velocity=0 nem sempre capturados corretos
Alguns arquivos MIDI usam note_on com velocity=0 para representar note_off. Se sua lógica não trata ambos esses casos corretamente, pode deixar notas abertas indefinidamente, o que pode causar notas extras aparecendo.
Solução: Garanta que o seu código trata tanto mensagens note_off quanto note_on com velocity=0 para fechar as notas corretamente.
python
if msg.type == 'note_on' and msg.velocity > 0:
# start nota
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
# stop nota
Essa parte você já tem, mas fique atento se está atualizada.
2) Nota permanece "ativa" se não há eventos finais correspondentes
Se o arquivo MIDI não possui eventos note_off ou equivalentes para algumas notas, seu código pode deixar notas abertas indefinidamente.
Solução: Ao final da leitura dos eventos, feche notes abertas:
python
# Após o loop que lê msgs
for note, start_time in note_on_times.items():
end_time = midi_file.length # pode fechar nota no final da música
duration = end_time - start_time
notes.append((start_time, note, duration))
3) Múltiplos canais MIDI ou instrumentos diferentes
Se seu MIDI tem vários canais e instrumentos, mas seu visualizador não está distinguindo canais, talvez esteja mesclando todas as notas.
Solução: Se quiser, filtre apenas o canal/midi que deseja visualizar. Ou adapte o código para ler e agrupar notas por canal.
User
sim
Assistant
Claro! Abaixo está o código completo com a adaptação para um correto emparelhamento das notas note_on e note_off, permitindo múltiplas ocorrências simultâneas da mesma nota, garantindo que só as notas realmente presentes no MIDI sejam visualizadas.
Também mantém o filtro para o intervalo do piano padrão (21 a 108) e integra-se ao visualizador avançado com vídeo no background, redimensionamento da janela e controles:
python
User
parece que está tocando em outra tonalidade
Assistant
Quando as notas exibidas parecem “tocando em outra tonalidade” (ex.: o acorde visualizado não corresponde ao esperado), geralmente isso não é um problema do visualizador exibir notas fora do arquivo MIDI, mas sim uma questão relacionada a:
Transposição involuntária das notas MIDI no visualizador
Interpretação incorreta das notas em números MIDI (0-127)
Ou um erro na posição horizontal que desloca as notas para teclas erradas.
Diagnóstico e soluções a partir do seu código atual
1) Verifique se as notas MIDI estão sendo usadas com os valores originais (0-127)
Você deve usar o número da nota MIDI diretamente para mapear no piano, sem alterar ou transpor. No seu código, isso está definido como:
python
MIN_VISIBLE_NOTE = 21 # A0 - primeira nota do piano padrão de 88 teclas
MAX_VISIBLE_NOTE = 108 # C8 - última nota do piano padrão
E o cálculo da posição horizontal é:
python
def white_key_index(note):
# Conta quantas teclas brancas têm até a nota dada
...
É crucial garantir que os índices e posições das teclas não tenham offsets ou mudanças.
2) Verifique se o MIDI que você está usando realmente contém as notas corretas
Rode um visualizador MIDI (como MuseScore, Midieditor ou outro) e confirme quais notas estão presentes no arquivo MIDI. Isso elimina dúvidas no arquivo.
3) Verifique o cálculo de posição horizontal da tecla no seu visualizador
O cálculo comum para o índice da tecla branca funciona assim:
python
def is_black_key(note):
return ((note - 21) % 12) in [1, 3, 6, 8, 10]
def white_key_index(note):
count = 0
for n in range(21, note):
if not is_black_key(n):
count += 1
return count
Confirme se essa conta corresponde ao layout correto do piano padrão, onde as teclas brancas são contadas baseadas nos números das notas MIDI.
4) Possível erro de base deslocada (offset)
Se as notas parecem transpostas, pode haver um deslocamento entre as notas MIDI e as teclas da imagem do piano. Por exemplo, seu visualizador considera o primeiro A (midi 21) para o índice 0, mas se o piano visualizado começa em C, isso vai causar inversão.
User
sim
Assistant
Ok! Vou ajudar a depurar e garantir que as notas exibidas estejam exatamente iguais às do seu arquivo MIDI, sem transposição errada.
Vou modificar o código para imprimir no console o valor exato da nota MIDI note com seu tempo de início, além de mostrar sua posição calculada no teclado. Assim podemos verificar se o mapeamento está correto.
Também farei um ajuste para garantir que o intervalo MIN_VISIBLE_NOTE a MAX_VISIBLE_NOTE coincide exatamente com as notas do seu MIDI — se precisar pode ajustar no código (por padrão está 21 a 108).
Código com debug para verificar notas e suas posições:
python
# ... [mantém todo o código anterior, só adiciona:
for start, note, duration in sorted(notes, key=lambda x: x[0]):
idx = white_key_index(note)
print(f"Nota MIDI {note} começa em {start:.3f}s, duração {duration:.3f}s, índice tecla branca: {idx}")
Para te ajudar, segue trecho central modificado com prints e proteção:
python
for start, note, duration in notes:
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
print(f"Descartando nota fora do range: {note}")
continue
idx = white_key_index(note)
if idx is None:
print(f"Nota {note} com índice inválido, ignorando.")
continue
print(f"Nota MIDI {note} começa em {start:.3f}s, idx da tecla branca: {idx}")
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = calc_velocity(h) * speed_multiplier
time_since_appear = current_time - (start - PREROLL / speed_multiplier)
if 0 <= time_since_appear <= PREROLL / speed_multiplier:
y = velocity * time_since_appear - h
if is_black_key(note):
x = idx * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = idx * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
User
como: Rode o programa no terminal/console com esse debug ligado.
Assistant
Para rodar o programa Python com o debug ativado (ou seja, para que ele imprima no terminal as informações das notas que está lendo e exibindo), siga estes passos simples:
Passo a passo para rodar seu programa com debug no terminal:
Abra um terminal/console no seu sistema
No Windows: Pode usar o Prompt de Comando (cmd) ou PowerShell
No macOS/Linux: Use o Terminal
Navegue até a pasta onde seu script Python está salvo
Supondo que seu script está em C:\Users\SeuUsuario\Projetos\MidiVisualizer no Windows, use:
powershell
cd C:\Users\SeuUsuario\Projetos\MidiVisualizer
No macOS/Linux, a sintaxe é semelhante:
bash
cd /caminho/para/seu/script
Abra seu script Python com o código atualizado (com prints para debug), por exemplo visualizador_midi.py
Execute o script usando o Python pelo terminal
Se você usa Python 3 instalado como python3:
bash
python3 visualizador_midi.py
Ou, se o comando for python (verifique sua instalação):
bash
python visualizador_midi.py
O que esperar:
O programa vai iniciar e imprimir no terminal linhas com texto parecido com:
code
Nota MIDI 60 começa em 0.000s, idx da tecla branca: 24
Nota MIDI 64 começa em 0.000s, idx da tecla branca: 28
Nota MIDI 67 começa em 0.000s, idx da tecla branca: 31
...
Cada linha corresponde a uma nota que o programa está lendo do seu arquivo MIDI, com o tempo em que ela deve começar, e o índice horizontal onde será desenhada.
Caso veja notas que NÃO deveriam estar no seu arquivo MIDI, agora você tem o número da nota para diagnosticar.
Importante
Tenha certeza que você salvou a última versão do código com as linhas de print para ver o debug.
Se estiver usando alguma IDE (como VS Code, PyCharm), também é possível ver essa saída em seus terminais internos.
Para parar o programa, use CTRL+C no terminal ou feche a janela do visualizador.
Se quiser, posso te ajudar a interpretar os valores que aparecerem nesses prints, e a ajustar o código para filtrar notas indesejadas ou com problemas de canal, transposição, etc.
Quer que eu te auxilie com isso?
User
como: Tenha certeza que você salvou a última versão do código com as linhas de print para ver o debug.
Assistant
Claro! Explico como garantir que o seu arquivo Python contém as linhas de print para debug e como salvar a última versão corretamente:
Como garantir que você salvou a última versão do código com os prints de debug:
Passo 1: Abra seu arquivo Python com um editor de texto ou IDE
Pode ser o Notepad/Bloco de Notas (Windows), TextEdit (macOS, modo texto), ou
Editores mais avançados, como VS Code, PyCharm, Sublime Text, Atom etc.
Passo 2: Localize a parte do código onde adicionamos os prints para debug
Exemplo:
python
for start, note, duration in notes:
idx = white_key_index(note)
print(f"Nota MIDI {note} começa em {start:.3f}s, duração {duration:.3f}s, índice tecla branca: {idx}")
Essa linha print(...) é a que gera as mensagens no terminal com os dados das notas.
Passo 3: Faça as alterações necessárias para ativar o debug
Se você ainda não tem a linha print no lugar certo, adicione-a no loop que processa e desenha as notas (por exemplo, próximo ou antes do código que desenha as notas).
Passo 4: Salve o arquivo depois de editar
No seu editor, clique em Arquivo > Salvar (ou use o atalho comum, geralmente Ctrl+S no Windows/Linux ou Cmd+S no macOS).
Certifique-se que está salvando no mesmo local/arquivo que você vai executar no terminal.
Passo 5: Feche o editor (opcional) e execute o arquivo no terminal novamente
Dicas extra para evitar confusão com versões antigas
Verifique o nome do arquivo .py que você está rodando no terminal e se ele corresponde ao arquivo que você editou e salvou.
Às vezes, temos mais de uma cópia do script e acabamos editando uma, mas executando outra.
Para confirmar, você pode inserir um print("Script carregado com debug") no topo do código e verificar se essa mensagem aparece quando executar.
Recapitulando:
Edite seu arquivo .py no editor.
Adicione/modifique as linhas print para debug.
Salve o arquivo (Ctrl+S/Cmd+S).
Execute o script salvo no terminal.
Veja as mensagens no terminal como esperado.
Se precisar, posso ajudar você a criar um pequeno trecho exato com o print para inserir, ou ajudar a configurar seu ambiente para facilitar salvar e rodar. Quer?
User
BPM detectado: 70.00007000007
Nota MIDI 55 começa em 6.857s, duração 0.857s, índice tecla branca: 20
Nota MIDI 52 começa em 6.857s, duração 0.857s, índice tecla branca: 18
Nota MIDI 48 começa em 6.857s, duração 0.857s, índice tecla branca: 16
Nota MIDI 57 começa em 8.571s, duração 0.857s, índice tecla branca: 21
Nota MIDI 60 começa em 8.571s, duração 0.857s, índice tecla branca: 23
Nota MIDI 64 começa em 8.571s, duração 0.857s, índice tecla branca: 25
Nota MIDI 60 começa em 9.857s, duração 0.857s, índice tecla branca: 23
Nota MIDI 57 começa em 9.857s, duração 0.857s, índice tecla branca: 21
Nota MIDI 53 começa em 9.857s, duração 0.857s, índice tecla branca: 19
Nota MIDI 62 começa em 11.143s, duração 1.714s, índice tecla branca: 24
Nota MIDI 59 começa em 11.143s, duração 1.714s, índice tecla branca: 22
Nota MIDI 55 começa em 11.143s, duração 1.714s, índice tecla branca: 20
Assistant
Obrigado por mandar os valores! Vamos analisar:
O que achamos nos seus prints:
Nota MIDI
Tempo início (s)
Duração (s)
Índice tecla branca
55
6.857
0.857
20
52
6.857
0.857
18
48
6.857
0.857
16
57
8.571
0.857
21
60
8.571
0.857
23
64
8.571
0.857
25
60
9.857
0.857
23
57
9.857
0.857
21
53
9.857
0.857
19
62
11.143
1.714
24
59
11.143
1.714
22
55
11.143
1.714
20
Observações:
Notas MIDI e índice da tecla branca:
O índice da tecla branca está consistente e próximo:
Exemplo: Nota 60 (Dó central) → índice 23
Sabemos que numa escala de piano padrão, o Dó central (C4) é a nota MIDI 60 e está na posição certa no teclado.
Notas diferentes das de Dó maior?
Você mencionou um acorde de Dó maior: Dó (60), Mi(64), Sol(67).
No entanto, as notas exibidas incluem 48, 52, 53, 55, 57, 59, 62 — que são outros semitons.
O que pode ser?
Seu arquivo midi completo obviamente tem várias notas e possivelmente vários acordes em sequência.
Você pode estar confundindo as notas que aparecem em diferentes momentos da música (não necessariamente todas tocam ao mesmo tempo).
O trecho do seu log mostra notas em tempos diferentes (6.857s, 8.571s, 9.857s, 11.143s), portanto é a música tocando diferentes acordes e notas ao longo do tempo.
Recomendo:
Verifique o trecho da música onde seu acorde Dó maior aparece (normalmente perto do início, tempo zero ou próximo).
User
sim
Assistant
Perfeito! Vou preparar para você um trecho adicional que agrupa as notas tocando simultaneamente em “acordes” (notas que começam no mesmo tempo) e imprime no console de forma clara. Isso vai facilitar ver exatamente quais notas formam cada acorde e quando eles acontecem.
Depois, pode usar isso para validar a leitura do seu MIDI e ajustar o visualizador conforme a necessidade.
Código para agrupar e imprimir acordes no console
Adicione esse trecho após a leitura e preenchimento da lista notes (ou logo antes do loop principal do visualizador):
python
from collections import defaultdict
# Agrupar notas por tempo de início arredondado a 3 casas decimais (pode ajustar precisão)
acordes = defaultdict(list)
for start, note, duration in notes:
tempo_chave = round(start, 3) # agrupa notas que começam praticamente ao mesmo tempo
acordes[tempo_chave].append(note)
# Ordenar tempos e imprimir acordes no console
print("\nAcordes detectados no MIDI (notas começando juntas):")
for tempo in sorted(acordes.keys()):
notas_no_acorde = acordes[tempo]
notas_str = ", ".join(str(n) for n in sorted(notas_no_acorde))
print(f"Tempo {tempo:.3f} s: Notas MIDI [{notas_str}]")
Exemplo de saída possível
code
Acordes detectados no MIDI (notas começando juntas):
Tempo 0.000 s: Notas MIDI [60, 64, 67]
Tempo 2.571 s: Notas MIDI [55, 59]
Tempo 4.285 s: Notas MIDI [57, 60, 64]
...
Como usar
Rode seu script com isso incluído.
Observe no terminal os grupos de notas que tocam juntas, que formam um acorde.
Confirme se eles correspondem com as notas e os acordes esperados (ex: Dó maior sendo notas 60,64,67 juntas).
Próximos passos para você:
Verifique se o acorde correto aparece no tempo correto.
Se precisar, adicione filtros para exibir ou destacar no visualizador só os acordes que quiser.
Me avise se quiser ajuda para, por exemplo, destacar visualmente um acorde específico, ou criar filtros por canal e faixa temporal.
Se preferir, posso integrar isso diretamente no seu código completo com visualização, para imprimir no começo ou em tempo real, e criar destaque da nota no visual.
Quer que eu prepare essa versão integrada e te envie?
User
from collections import defaultdict
Agrupar notas por tempo de início arredondado a 3 casas decimais (pode ajustar precisão)
acordes = defaultdict(list)
for start, note, duration in notes:
tempo_chave = round(start, 3) # agrupa notas que começam praticamente ao mesmo tempo
acordes[tempo_chave].append(note)
Ordenar tempos e imprimir acordes no console
print("\nAcordes detectados no MIDI (notas começando juntas):")
for tempo in sorted(acordes.keys()):
notas_no_acorde = acordes[tempo]
notas_str = ", ".join(str(n) for n in sorted(notas_no_acorde))
print(f"Tempo {tempo:.3f} s: Notas MIDI [{notas_str}]")
Assistant
Esse código está correto e vai agrupar as notas que começam praticamente ao mesmo tempo em "acordes", imprimindo no console os tempos e as notas MIDI correspondentes.
Como usar este trecho no seu visualizador MIDI:
Insira esse bloco após carregar e processar todas as notas da sua lista notes (ou seja, depois do trecho onde você já tem notes = [...] preenchido com (start, note, duration)).
Ao executar o seu script, você verá no terminal algo parecido com:
code
Acordes detectados no MIDI (notas começando juntas):
Tempo 0.000 s: Notas MIDI [60, 64, 67]
Tempo 1.143 s: Notas MIDI [55, 59]
Tempo 2.285 s: Notas MIDI [57, 60, 64]
...
Próximos passos
Com essas informações, você pode conferir se o visualizador está realmente mostrando as notas que aparecem aqui.
Se quiser, posso ajudar a modificar seu visualizador para destacar todos os acordes, ou apenas determinados acordes em momentos específicos.
Também posso ajudar a filtrar, agrupar por canal, ou limitar a visualização a um intervalo de tempo.
Se quiser, posso integrar esse código ao seu visualizador completo e lhe enviar. Deseja?
User
Tempo 6.857 s: Notas MIDI [48, 52, 55]
Tempo 8.571 s: Notas MIDI [57, 60, 64]
Tempo 9.857 s: Notas MIDI [53, 57, 60]
Tempo 11.143 s: Notas MIDI [55, 59, 62]
Assistant
Obrigado por compartilhar os acordes detectados!
Vamos interpretar essas notas e verificar se correspondem ao que você espera.
Análise dos acordes impressos:
Tempo (s)
Notas MIDI
Notas Musicais
Comentário
6.857
48, 52, 55
C3, E3, G3
Acorde dó maior uma oitava abaixo do dó central
8.571
57, 60, 64
A3, C4, E4
Acorde Lá menor (Am)
9.857
53, 57, 60
F3, A3, C4
Acorde Fá maior (F)
11.143
55, 59, 62
G3, B3, D4
Acorde Sol maior (G)
Observações importantes:
As notas que você vê são mesmo notas MIDI padrão e formam acordes bem conhecidos.
As notas do acorde de Dó maior (C major) aparecem no tempo 6.857s (C-E-G, notas 48-52-55).
Outros acordes aparecem depois, conforme a progressão do seu arquivo MIDI.
Se você esperava o acorde de Dó maior em um tempo diferente (ex.: perto do segundo 0), provavelmente o trecho inicial da música está silencioso ou tocando outras notas.
Se quiser destacar apenas o acorde de Dó maior (60,64,67) no visualizador:
Como seu acorde está aparecendo em uma oitava abaixo (notas 48,52,55), pode ser que seu MIDI esteja com registros mais baixos, ou diferentes oitavas.
Sugestão para destacar um acorde específico (exemplo: notas 48, 52 e 55):
No loop de desenho da nota no visualizador:
python
# exemplos de notas do acorde dó maior (numa oitava específica):
do_maior = {48, 52, 55}
for start, note, duration in notes:
# Mostrar apenas notas do acorde dó maior
if note not in do_maior:
continue
# código restante para desenhar a nota igual antes
Você pode alterar o conjunto do_maior para qualquer conjunto de notas que queira destacar.
Próximos passos
Se quiser posso ajudar a modificar o visualizador para filtrar e destacar os acordes exatos que deseja.
Posso ajudar a ajustar o intervalo de reprodução para mostrar só uma parte específica da sua música.
Também posso ajudar a interpretar o arquivo MIDI para melhor compreensão dos acordes e registros usados.
Se desejar, posso te ajudar a modificar seu código para filtrar e mostrar os acordes como você quiser, ou melhorar a interface para escolha dinâmica.
Quer que eu faça isso?
User
então pode ser o piano. no visualizador está tocando tambem teclas pretas neste exemplo
Assistant
Exato, se o visualizador está mostrando notas que você espera serem brancas, mas aparecem também teclas pretas ativas, isso pode ser simplesmente porque as notas do arquivo MIDI incluem notas pretas (sustenidos/ bemóis) — e o visualizador está corretamente representando essas notas, já que elas fazem parte do acorde ou da música.
Sobre o acorde de Dó maior
O acorde de Dó maior é formado por Dó (C), Mi (E) e Sol (G).
Na escala temperada, essas notas podem aparecer como notas básicas (teclas brancas) ou com variações (ex. Dó# ou Ré# são teclas pretas, mas não fazem parte do acorde puro de Dó maior).
Se o arquivo MIDI tem adornos, extensões ou notas adicionais, teclas pretas serão tocadas.
Se você quer só notar as notas brancas
Você pode filtrar no código as notas que são pretas e não exibi-las/remover da visualização.
Exemplo para filtrar notas pretas:
python
for start, note, duration in notes:
if is_black_key(note):
continue # pula notas pretas
# desenha apenas notas brancas
Mas cuidado: isso pode ocultar partes importantes da música se houver notas pretas legítimas.
Se acha que o visualizador está “marcando” teclas pretas sem elas aparecerem no arquivo MIDI
Pode ser um bug, e sugiro conferir:
Que as notas desenhadas correspondem às realmente encontradas, usando os prints que você já tem.
Que o desenho do teclado reage apenas às notas que estão na lista ativa.
Que a lógica para detectar is_black_key esteja correta.
Double check: Função correta para identificar notas pretas
Essa é a fórmula padrão para teclas pretas no piano (C dur), portanto deve funcionar corretamente.
Recomendo
Confirmar quais notas (brancas e pretas) seu MIDI contém para aquele trecho da música.
Se quiser, posso te ajudar a refinar para destacar melhor as teclas ativas e diferenciar visualmente brancas e pretas.
Se desejar ocultar as teclas pretas na visualização das notas (não no piano), posso ajudar a aplicar esse filtro.
Quer que eu ajude a fazer isso no seu código?
Ou quer que eu mostre como alterar as cores de forma mais evidente para distinguir as teclas?
User
o primeiro acorde que está aparecendo no visualizador junto com o piano é re sustenido maior
Assistant
Obrigado por confirmar! Se o primeiro acorde que aparece no visualizador é Ré sustenido maior (D# maior) e não o acorde esperado (Dó maior), significa que seu arquivo MIDI realmente começa tocando esse acorde ou que a leitura do MIDI está correta e o visualizador está mostrando a realidade do arquivo.
O que fazer agora?
1) Confirme o conteúdo do arquivo MIDI
Use um visualizador MIDI externo (MuseScore, MidiEditor, etc.) para abrir seu arquivo e verificar quais acordes aparecem no início.
Se o acorde realmente começa com D# maior (notas D#(63), G(67), A#(70)), então o visualizador está certo.
2) Se quiser visualizar/Destacar apenas certas notas ou acordes no seu visualizador
Você pode filtrar as notas que aparecem com base numa lista específica, por exemplo, o conjunto das notas da escala/acorde que deseja mostrar.
Exemplo: visualizar só notas do Dó maior (C, E, G)
python
notas_para_mostrar = {60, 64, 67} # Dó, Mi, Sol
for start, note, duration in notes:
if note not in notas_para_mostrar:
continue
# código para desenhar a nota
3) Para facilitar a identificação e correção, imprima os acordes na ordem e verifique o que acontece no tempo zero:
Use o agrupamento de acordes que você já tem e veja o primeiro acorde ou as notas que aparecem no tempo inicial.
Comparando com o visualizador externo, você verifica se está coerente.
4) Se seu arquivo MIDI estiver errado, pode reexportar com o acorde correto
Às vezes o arquivo MIDI tem “intro” ou acordes diferentes no começo.
5) Se preferir que eu ajude a filtrar o visualizador para ignorar notas/teclas e só mostrar o acorde que você deseja
Exemplo: só visualizar notas específicas e ignorar as outras, para focar na visualização esperada.
Ou podemos adicionar opção para você escolher o acorde/acorde customizado parâmetro para visualização.
Quer que eu faça para você:
Um filtro para exibir somente as notas do acorde Dó maior ou outro acorde que preferir?
Ou um destaque visual mais forte para as notas do acorde esperado?
Ou ajuda para interpretar o arquivo MIDI e ajustar a visualização?
Fique à vontade para pedir!
User
o visualizador está tocando re sustenido maior quanto o arquivo midi é o acorde de do maior
Assistant
Se o seu visualizador está mostrando um acorde de Ré sustenido maior (D# maior) enquanto o arquivo MIDI é realmente um acorde de Dó maior (C, E, G), isso indica que provavelmente há algum problema de desalinhamento entre os valores MIDI lidos e a forma como o visualizador posiciona ou interpreta as notas.
Possíveis causas para essa discrepância
Erro de MIN_VISIBLE_NOTE incorreto / Offset errada
O visualizador usa MIN_VISIBLE_NOTE = 21 para alinhar notas MIDI do piano começando no A0. Se o piano no visualizador estiver deslocado, as posições das teclas podem não correspondem às corretas nas notas MIDI.
O índice da tecla branca (função white_key_index) pode estar com cálculo incorreto
Caso o cálculo que converte a nota MIDI em índice de tecla branca esteja deslocado ou errado, as notas podem ser desenhadas em teclas erradas, parecendo outro acorde.
Problema de transposição explícita ou implícita
O visualizador pode estar adicionando algum valor (offset) à nota MIDI antes de desenhar — isso causa uma transposição errada.
Uso incorreto da montagem do teclado
O teclado deve iniciar bem na nota MIDI 21 (A0). Se ele estiver começando em uma nota diferente, ou se o cálculo do index não levar isso em consideração, o efeito será um desvio.
Diagnóstico e correção passo a passo
1) Confirme que FIRST_MIDI_NOTE está definido como 21 (A0)
2) Revise a função white_key_index que converte a nota em índice da tecla branca
Aqui está uma variante correta que considera o offset e conta corretamente:
python
def white_key_index(note):
if note < MIN_VISIBLE_NOTE or note > MAX_VISIBLE_NOTE:
return None
count = 0
for n in range(MIN_VISIBLE_NOTE, note):
if not is_black_key(n):
count += 1
return count
3) Assegure que is_black_key calculate corretamente as teclas pretas
python
User
sim
Assistant
Perfeito! Vou preparar um trecho de código para você inserir no loop onde as notas são desenhadas, com prints detalhados para ajudar a identificar se o índice da tecla branca está correto para cada nota, e assim entender se está ocorrendo deslocamento que causa visualização errada do acorde.
Trecho com prints para diagnóstico no momento do desenho:
python
for start, note, duration in notes:
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
continue # Ignorar notas fora do intervalo do piano
idx = white_key_index(note)
if idx is None:
print(f"[DEBUG] Nota {note} tem índice inválido para tecla branca, descartando.")
continue
# DEBUG: imprimir nota MIDI, índice da tecla branca e se é preta ou branca
tipo_tecla = "Preta" if is_black_key(note) else "Branca"
print(f"[DEBUG] Nota MIDI: {note}, Índice tecla branca: {idx}, Tipo tecla: {tipo_tecla}")
# Continue com o cálculo da posição e desenho da nota
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = calc_velocity(h) * speed_multiplier
time_since_appear = current_time - (start - PREROLL / speed_multiplier)
if 0 <= time_since_appear <= PREROLL / speed_multiplier:
y = velocity * time_since_appear - h
if is_black_key(note):
x = idx * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = idx * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
O que esse código faz
Imprime no console, para cada nota desenhada:
User
BPM detectado: 70.00007000007
Nota MIDI 55 começa em 6.857s, duração 0.857s, índice tecla branca: 20
Nota MIDI 52 começa em 6.857s, duração 0.857s, índice tecla branca: 18
Nota MIDI 48 começa em 6.857s, duração 0.857s, índice tecla branca: 16
Nota MIDI 57 começa em 8.571s, duração 0.857s, índice tecla branca: 21
Nota MIDI 60 começa em 8.571s, duração 0.857s, índice tecla branca: 23
Nota MIDI 64 começa em 8.571s, duração 0.857s, índice tecla branca: 25
Nota MIDI 60 começa em 9.857s, duração 0.857s, índice tecla branca: 23
Nota MIDI 57 começa em 9.857s, duração 0.857s, índice tecla branca: 21
Nota MIDI 53 começa em 9.857s, duração 0.857s, índice tecla branca: 19
Nota MIDI 62 começa em 11.143s, duração 1.714s, índice tecla branca: 24
Nota MIDI 59 começa em 11.143s, duração 1.714s, índice tecla branca: 22
Nota MIDI 55 começa em 11.143s, duração 1.714s, índice tecla branca: 20
[DEBUG] Nota MIDI: 55, Índice tecla branca: 20, Tipo tecla: Preta
[DEBUG] Nota MIDI: 52, Índice tecla branca: 18, Tipo tecla: Branca
[DEBUG] Nota MIDI: 48, Índice tecla branca: 16, Tipo tecla: Preta
[DEBUG] Nota MIDI: 57, Índice tecla branca: 21, Tipo tecla: Branca
[DEBUG] Nota MIDI: 60, Índice tecla branca: 23, Tipo tecla: Preta
[DEBUG] Nota MIDI: 64, Índice tecla branca: 25, Tipo tecla: Branca
[DEBUG] Nota MIDI: 60, Índice tecla branca: 23, Tipo tecla: Preta
[DEBUG] Nota MIDI: 57, Índice tecla branca: 21, Tipo tecla: Branca
[DEBUG] Nota MIDI: 53, Índice tecla branca: 19, Tipo tecla: Preta
[DEBUG] Nota MIDI: 62, Índice tecla branca: 24, Tipo tecla: Branca
[DEBUG] Nota MIDI: 59, Índice tecla branca: 22, Tipo tecla: Branca
[DEBUG] Nota MIDI: 55, Índice tecla branca: 20, Tipo tecla: Preta
Assistant
Obrigado pelas informações! A partir do debug, percebo que algumas notas que você esperava serem teclas brancas estão marcadas como pretas. Por exemplo:
Nota MIDI 60 (Dó central) aparece como tecla PRETA — o que é incorreto, pois 60 é uma tecla branca (Dó).
Esse é o motivo pelo qual o visualizador está mostrando a tonalidade errada, notas deslocadas e acordes confusos.
Por que isso está acontecendo?
A sua função is_black_key(note) está calculando o tipo da tecla com base no módulo 12 relativo a MIN_VISIBLE_NOTE, veja:
O problema é que o padrão para detectar teclas pretas em relação ao Dó (nota 60) deveria ser feito em torno do valor 0 representando o Dó, e não do MIN_VISIBLE_NOTE.
Se MIN_VISIBLE_NOTE é 21 (nota A0 no piano), o cálculo está errado para o centro do teclado.
Como corrigir a função is_black_key(note)?
Você deve calcular o semitom relativo a C (nota 0 no ciclo) em vez de relativo ao seu MIN_VISIBLE_NOTE.
O padrão das teclas pretas em uma oitava conta do 0=Dó (C) assim:
Pretas = notas com semitom relativo no [1(C#), 3(D#), 6(F#), 8(G#), 10(A#)]
Assim, a implementação correta deve ser:
python
def is_black_key(note):
semitom_relativo = (note - 12) % 12 # considerando C4 = 60, C0 = 12; ajusta para ciclo baseado em C
return semitom_relativo in [1, 3, 6, 8, 10]
Ou, se quiser simplificar e assumir C = 0:
python
def is_black_key(note):
# Nota 60 = C4. 60 % 12 = 0 significa Dó.
return (note % 12) in [1, 3, 6, 8, 10]
Refaça o teste e veja se as notas como 60 são identificadas como tecla branca;
Observe se a visualização mostra o acorde de Dó maior corretamente;
Execute novamente o debug para conferir “Tipo tecla: Branca” ou “Preta” correspondente.
Se quiser, posso montar para você o trecho do código completo já com essa correção. Quer?
User
codigo completo com as correções
Assistant
Claro! Aqui está o seu código completo com a correção da função is_black_key para identificar corretamente as teclas pretas (baseando o cálculo no valor da nota MIDI módulo 12, padrão C = 0), garantindo que as notas do acorde sejam identificadas e exibidas corretamente.
python
User
precisa de que a nota seja visualizada em sua duração, ou seja, o piano mantem precionado dependendo da duração da nota
Assistant
Entendi! Você quer que a nota visualizada tenha um retângulo com altura proporcional à duração, e que ele desça no tempo de forma que a ponta inferior do retângulo alcance a tecla exatamente quando a nota “começa” a ser tocada, depois o retângulo (nota) continue descendo mantendo a tecla “pressionada” até o final da sua duração.
Como implementar isso?
Defina a altura do retângulo da nota proporcional à duração — isso você já tem.
Calcule a posição vertical (Y) da nota de forma que:
Quando a ponta inferior do retângulo (y + altura) alcança o teclado, a nota começa a ser tocada (tempo start).
O retângulo inteiro começa a aparecer preroll segundos antes na parte superior da área visível e desce.
Durante a duração da nota, o retângulo continua descendo ao longo do tempo.
Quando a nota terminada, o retângulo desaparece (ou sai da tela).
Cálculo da posição vertical Y da nota ao longo do tempo
Suponha:
t = tempo atual na visualização
start = tempo da nota começar
duration = tempo de duração da nota
PREROLL = tempo que a nota leva para descer da parte superior até o teclado (antes de começar)
visible_height = altura da área de descida (até o teclado)
Regras para Y(t):
A nota começa a aparecer na posição topo (y = -altura da nota), no tempo: t = start - PREROLL
Quando t = start (início da nota), ponta inferior do retângulo está no teclado: y + h = visible_height
Durante a duração a nota continua descendo (visualmente que a tecla está “mantida”)
Quando t = start + duration, o retângulo termina sua descida (deixa de existir)
Fórmula ideal
Dividimos o movimento da nota em duas fases:
Entrada da nota (preroll):
Para t em [start - PREROLL, start], a nota “entra” descendo:
Claro! Aqui está o código completo atualizado com a visualização das notas mantendo a tecla pressionada durante toda a duração da nota, incluindo:
Retângulo da nota com altura proporcional à duração;
Nota deslizando do topo até o teclado (“preroll”);
Durante a duração, o retângulo continua descendo, simbolizando que a tecla está pressionada;
Após a duração, a nota desaparece;
Integração com vídeo no background, redimensionamento da janela, controle de velocidade e pausa.
python
User
o visualizador está mostrando as teclas piscando e o retangulo que representa as notas estão passando um pouco do começo do desenho do piano para que a animação aja
Assistant
Esse comportamento de as teclas "piscarem" e os retângulos das notas ultrapassarem um pouco o começar do desenho do piano acontece normalmente por causa do modo como a animação está sincronizada e como as posições são calculadas — especialmente se o retângulo da nota, que corresponde à duração, vai descendo enquanto a tecla permanece destacada.
Aqui estão alguns pontos e sugestões para melhorar e corrigir esses efeitos:
1) Ajuste fino da posição de início da tecla versus posição da ponta da nota
No cálculo atual, o retângulo da nota “desce” e a ponta inferior do retângulo (y + h) atinge a base do teclado na posição y = visible_height.
Porém, se a tecla em si está desenhada começando exatamente em HEIGHT - PIANO_HEIGHT, e o retângulo é desenhado com a coordenada y (topo do retângulo), a ponta pode ultrapassar um pouco essa borda visualmente.
Solução:
Você pode adicionar uma pequena margem (offset) para que o retângulo da nota pare exatamente um pouco antes da borda do teclado.
Ou desenhar o teclado um pouco “sobreposto” ao topo dela para cobrir a ponta.
Exemplo:
python
MARGIN_PIANO = 5 # pixels
# Na fórmula da posição da ponta, subtraia a margem
visible_height_effective = visible_height - MARGIN_PIANO
Use visible_height_effective no lugar de visible_height para o cálculo da posição da nota:
E também para definir onde a ponta do retângulo “bate”.
2) Controle o tempo da animação do destaque da tecla
Se o destaque da tecla “pisca” porque a animação de brilho dura tempo fixo e reaparece no loop, você pode:
Fazer com que a animação inicie exatamente na hora em que a nota chega (no tempo start) e vá até o fim da duração da nota.
Usar a duração real para controlar a intensidade do destaque, diminuindo a “fluidez de piscar”.
Exemplo de fade in e fade out da animação baseado na duração:
python
User
sim
Assistant
Claro! Aqui está o código completo atualizado com as correções para:
Aplicar uma pequena margem (offset) para que o retângulo da nota não ultrapasse o começo do desenho do piano;
Fazer a animação que destaca a tecla pressionada durar proporcionalmente à duração da nota, com fade suave;
Garantir que o piano seja desenhado depois das notas para ficar sempre em primeiro plano;
Atualizar a animação usando o delta_time para suavidade.
python
User
ainda as notas passam um pouco do piano e então elas voltam para cima ao chegar neste ponto e depois reproduzem parecendo que mas certo desincronia
Assistant
Esse comportamento de notas passando um pouco pelo piano, "voltando" para cima e depois descendo de novo, geralmente indica uma questão de sincronização da posição vertical das notas com o tempo e o ciclo de exibição, ou um erro no cálculo da posição Y em função do tempo atual.
Também pode estar relacionado a como você está limitando a exibição das notas no intervalo de tempo, causando “saltos” ou reaparecimento inesperado.
Diagnóstico provável
1) As notas devem ser exibidas apenas enquanto estão na área visível do score, e removidas/discartadas após saírem.
Se a posição Y passa do limite (por exemplo maior que HEIGHT ou teclado), a nota deveria deixar de ser desenhada.
Se você deixa o retângulo continuar a ser desenhado ao sair da tela, ou reinicia a posição vertical para cima (como um reset), dará a impressão de “piscadas” ou notas reaparecendo.
2) Sincronização do tempo e cálculo da posição
O cálculo da posição vertical y deve aumentar monotonamente para cada nota de acordo com o tempo, sem reset.
Se no seu código usamos time_since_appear e condicionais, certifique-se de que:
A nota só é desenhada quando o tempo cai entre: [start - PREROLL, start + duration + extra]
Fora desse intervalo, a nota não é desenhada nem reposicionada
Código com correção prática para evitar “volta para cima” das notas e garantir sincronização suave
Modifique a lógica de desenho das notas para algo parecido com:
python
User
sim
Assistant
Claro! Aqui está o seu código completo atualizado, com a lógica corrigida para:
Garantir que as notas não reapareçam "do topo" após saírem da área visível;
Limitar a exibição das notas a um intervalo contínuo e amplo (do preroll antes do início até um pouco após o fim da duração);
Garantir que as notas só sejam desenhadas enquanto visíveis na janela, evitando “saltos” e piscadas;
Aplicar a margem para que as notas não ultrapassem visualmente o piano;
Manter o piano desenhado depois das notas para o foreground.
Double-click launch in Nautilus file manager may not work; use terminal or a .desktop file.
Compilation Notes
Uses CMake.
Requires GLFW3, sr_gui, RtMidi17 (included in vendor), and optionally FFMPEG v4.2+ for video export.
Linux dependencies: xorg-dev, libgtk-3-dev, libnotify, libasound2-dev, plus FFMPEG dev libs if needed.
Development Background
Parses MIDI files to extract notes.
Visualizes scrolling notes with effects.
Focused on user feature requests and maintenance.
If you want, I can help you with:
How to set it up on your system.
How to run from command line efficiently.
Troubleshoot errors you get.
Customize visual appearance.
Export video/images from command line.
Just ask!
Como usar:
Instale dependências:
bash
pip install mido pygame python-rtmidi
Coloque um arquivo MIDI chamado exemplo.mid na mesma pasta, ou modifique o nome no código.
Rode o script:
bash
python visualizador_midi.py
O que este código faz?
Lê o arquivo MIDI e extrai eventos note_on.
Cada nota é desenhada como um retângulo verde (pode adaptar o tamanho, cor).
As notas "sobem" na tela conforme o tempo avança, simulando uma visualização scrolling simples.
Você pode pausar, melhorar a visualização, adicionar teclado, efeitos etc.
Se quiser, posso ajudar a expandir esse código para:
Mostrar instrumentos diferentes em cores diferentes
Suportar pausas, reinicios, controles no teclado
Exportar imagens ou vídeos da visualização
Ou integrar com áudio para tocar junto
Quer que eu faça um exemplo mais sofisticado? Ou quer ajuda para instalar e rodar esse básico?
import mido
import pygame
import sys
import time
# Configurações
WIDTH, HEIGHT = 800, 600
NOTE_HEIGHT = 10
SPEED = 0.5 # Velocidade da animação vertical
PIANO_HEIGHT = 100
# Notas referentes às teclas do piano (88 teclas do piano, de A0=21 a C8=108)
FIRST_NOTE = 21
NUM_NOTES = 88
# Inicializar pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Visualizador MIDI com Piano")
clock = pygame.time.Clock()
# Carregar arquivo MIDI
midi_file = mido.MidiFile('exemplo.mid')
# Extrair eventos note_on com tempo absoluto
notes = []
time_elapsed = 0
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
notes.append((time_elapsed, msg.note))
# Mapeamento das teclas pretas no teclado (index baseado na nota dentro das 12 semitons)
black_keys = [1, 3, 6, 8, 10] # notas pretas nos índices 0-11
# Gerar lista das teclas brancas e pretas entre 21 e 108
def is_black_key(midi_note):
return ((midi_note - 21) % 12) in black_keys
# Dimensões das teclas
white_key_width = WIDTH / 52 # Existem 52 teclas brancas num piano padrão
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
# Mapear nota midi para posição X do teclado (somente teclas brancas contam para posição)
def note_to_piano_x(note):
# Contar quantas teclas brancas tem até essa nota, para posicionar corretamente
white_key_pos = 0
for n in range(FIRST_NOTE, note):
if not is_black_key(n):
white_key_pos += 1
# Se a nota for preta, ajustar para posição próxima da branca à esquerda
x = white_key_pos * white_key_width
if is_black_key(note):
x -= black_key_width / 2 # deslocar preta para centro aproximado
return x
# Dicionário para controlar teclas ativadas: {note: tempo_de_desativar}
active_keys = {}
def note_to_y(note):
# Mapear nota para posição vertical (área de notas rolando)
return HEIGHT - PIANO_HEIGHT - (note - FIRST_NOTE) * ((HEIGHT - PIANO_HEIGHT) / NUM_NOTES)
# Tempo em segundos para manter a tecla com destaque após o evento
HIGHLIGHT_TIME = 0.3
start_ticks = pygame.time.get_ticks()
running = True
while running:
screen.fill((0, 0, 0))
current_time = (pygame.time.get_ticks() - start_ticks) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Desenhar notas scrollando na área de visualização
for note_time, note in notes:
y = note_to_y(note) - (current_time - note_time) * 100 * SPEED
if 0 < y < HEIGHT - PIANO_HEIGHT:
pygame.draw.rect(screen, (0, 255, 0), (WIDTH/2, y, 100, NOTE_HEIGHT))
# Atualizar teclas ativadas (com base no tempo)
for note_time, note in notes:
if current_time >= note_time and current_time <= note_time + HIGHLIGHT_TIME:
active_keys[note] = current_time + HIGHLIGHT_TIME
# Remover teclas que já passaram o tempo de destaque
to_remove = [note for note, t in active_keys.items() if t < current_time]
for note in to_remove:
del active_keys[note]
# Desenhar o teclado - teclas brancas
white_key_x = 0
for n in range(FIRST_NOTE, FIRST_NOTE + NUM_NOTES):
if not is_black_key(n):
color = (255, 255, 255)
if n in active_keys:
color = (255, 230, 180) # tecla branca destacada
pygame.draw.rect(screen, color, (white_key_x, HEIGHT - PIANO_HEIGHT, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (white_key_x, HEIGHT - PIANO_HEIGHT, white_key_width, white_key_height), 1)
white_key_x += white_key_width
# Desenhar teclas pretas *após* as brancas
white_key_x = 0
for n in range(FIRST_NOTE, FIRST_NOTE + NUM_NOTES):
if not is_black_key(n):
white_key_x += white_key_width
else:
x = white_key_x - black_key_width / 2
color = (0, 0, 0)
if n in active_keys:
color = (255, 100, 100) # tecla preta destacada vermelha clara
pygame.draw.rect(screen, color, (x, HEIGHT - PIANO_HEIGHT, black_key_width, black_key_height))
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
Como executar?
Instale as dependências, se ainda não tiver:
bash
pip install mido pygame python-rtmidi
Garanta um arquivo MIDI chamado exemplo.mid na mesma pasta (ou altere no código).
Rode o script com:
bash
python seu_script.py
O que esse código faz além do básico?
Desenha o teclado completo (88 teclas) na parte inferior.
Teclas brancas e pretas são desenhadas na posição correta, respeitando o layout do piano.
Quando uma nota está sendo "tocada" dentro de um intervalo curto em torno do seu tempo, a tecla correspondente está destacada (branco amarelo para teclas brancas, vermelho claro para pretas).
As notas continuam rolando para cima, e as teclas do piano refletem a atividade em tempo real que está visualizada.
Se quiser que a gente melhore a animação, adicione controles, ou suporte entrada MIDI ao vivo, é só avisar!
Quer que eu explique algum trecho do código também?
import mido
import pygame
import sys
# Configurações
WIDTH, HEIGHT = 800, 600
NOTE_HEIGHT = 10
SPEED = 0.5 # Velocidade da animação vertical
PIANO_HEIGHT = 100
FIRST_NOTE = 21
NUM_NOTES = 88
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Visualizador MIDI com Piano descendente")
clock = pygame.time.Clock()
midi_file = mido.MidiFile('exemplo.mid')
notes = []
time_elapsed = 0
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
notes.append((time_elapsed, msg.note))
black_keys = [1, 3, 6, 8, 10]
def is_black_key(midi_note):
return ((midi_note - 21) % 12) in black_keys
white_key_width = WIDTH / 52
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
def note_to_piano_x(note):
white_key_pos = 0
for n in range(FIRST_NOTE, note):
if not is_black_key(n):
white_key_pos += 1
x = white_key_pos * white_key_width
if is_black_key(note):
x -= black_key_width / 2
return x
# Agora a posição Y inicial das notas é no topo da área useful, ou seja, 0
NOTE_AREA_TOP = 0
def note_to_y_descending(note):
# Apenas a posição vertical da nota dentro do teclado (altura relativa)
# Podemos posicionar as notas próximas da tecla, por exemplo
return HEIGHT - PIANO_HEIGHT - (note - FIRST_NOTE) * ((HEIGHT - PIANO_HEIGHT) / NUM_NOTES)
HIGHLIGHT_TIME = 0.3
active_keys = {}
start_ticks = pygame.time.get_ticks()
running = True
while running:
screen.fill((0, 0, 0))
current_time = (pygame.time.get_ticks() - start_ticks) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Notas descendo (começam no topo e descem para o teclado)
for note_time, note in notes:
# Calcular a distância em pixels descendo:
y = NOTE_AREA_TOP + (current_time - note_time) * 100 * SPEED
# Só desenhar se estiver dentro da área visível (entre topo e teclas)
if 0 < y < HEIGHT - PIANO_HEIGHT:
pygame.draw.rect(screen, (0, 255, 0), (WIDTH/2, y, 100, NOTE_HEIGHT))
# Atualizar teclas ativadas
for note_time, note in notes:
if current_time >= note_time and current_time <= note_time + HIGHLIGHT_TIME:
active_keys[note] = current_time + HIGHLIGHT_TIME
to_remove = [note for note, t in active_keys.items() if t < current_time]
for note in to_remove:
del active_keys[note]
# Desenhar teclado (brancas)
white_key_x = 0
for n in range(FIRST_NOTE, FIRST_NOTE + NUM_NOTES):
if not is_black_key(n):
color = (255, 255, 255)
if n in active_keys:
color = (255, 230, 180)
pygame.draw.rect(screen, color, (white_key_x, HEIGHT - PIANO_HEIGHT, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (white_key_x, HEIGHT - PIANO_HEIGHT, white_key_width, white_key_height), 1)
white_key_x += white_key_width
# Pretas
white_key_x = 0
for n in range(FIRST_NOTE, FIRST_NOTE + NUM_NOTES):
if not is_black_key(n):
white_key_x += white_key_width
else:
x = white_key_x - black_key_width / 2
color = (0, 0, 0)
if n in active_keys:
color = (255, 100, 100)
pygame.draw.rect(screen, color, (x, HEIGHT - PIANO_HEIGHT, black_key_width, black_key_height))
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
Resumo:
A posição vertical das notas começa em NOTE_AREA_TOP (0, o topo da janela).
Quanto mais tempo passa desde o note_time, maior a distância y (descendo).
Quando y chega perto do teclado (área inferior), a nota "chega" à tecla correspondente.
Teclas do piano ficam iluminadas quando a nota está ativa.
Quer que eu te ajude a adaptar isso para receber entrada MIDI ao vivo, ou adicionar controles de pausa/play?
Ou deixar as notas desenhadas mais próximas ao piano, com largura proporcional à duração da nota?
import mido
import pygame
import sys
# Configuração da tela
WIDTH, HEIGHT = 800, 600
PIANO_HEIGHT = 100
# Número de teclas do piano padrão
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
FIRST_MIDI_NOTE = 21 # A0
LAST_MIDI_NOTE = FIRST_MIDI_NOTE + NUM_KEYS - 1
# Mapas para as teclas pretas (indices mod 12)
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
# Inicialização pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Visualizador MIDI estilo Synthesia")
clock = pygame.time.Clock()
# Carregando arquivo midi
midi_file = mido.MidiFile('exemplo.mid')
# Processar eventos note_on
# Armazenar notas como (tempo_em_segundos, nota_midi, duração_em_segundos)
notes = []
time_elapsed = 0.0
# Para duração calculamos o tempo quando a nota_off ocorre
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
note_on_times[msg.note] = time_elapsed
elif (msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0)):
if msg.note in note_on_times:
start = note_on_times[msg.note]
duration = time_elapsed - start
if duration <= 0:
duration = 0.1 # duração mínima
notes.append((start, msg.note, duration))
del note_on_times[msg.note]
# Dimensão das teclas
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
# Função para identificar se uma nota é tecla preta
def is_black_key(midi_note):
return ((midi_note - FIRST_MIDI_NOTE) % 12) in BLACK_KEY_INDICES
# Função para retorno do índice da tecla branca para uma nota midi
def white_key_index(note):
# Conta quantas teclas brancas antes da nota
count = 0
for n in range(FIRST_MIDI_NOTE, note):
if not is_black_key(n):
count += 1
return count
# Função para desenhar o teclado no rodapé
def draw_piano(active_notes):
# Teclas brancas
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
color = (255, 255, 255)
if n in active_notes:
color = (255, 230, 180) # realce
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
# Teclas pretas
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if is_black_key(n):
# A tecla preta fica centralizada entre as brancas adjacentes
x = white_key_index(n) * white_key_width - black_key_width / 2
color = (0, 0, 0)
if n in active_notes:
color = (255, 100, 100)
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
# Parâmetros de animação
NOTE_SPEED = 200 # pixels por segundo descendo
NOTE_WIDTH_MULT = 0.9 # multiplicar largura da tecla branca para largura da nota
NOTE_HEIGHT_MIN = 4 # altura mínima da nota
NOTE_HEIGHT_MAX = 40 # altura máxima da nota (baseada na duração)
# Loop principal
start_ticks = pygame.time.get_ticks()
running = True
while running:
screen.fill((0, 0, 0))
current_time = (pygame.time.get_ticks() - start_ticks) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Ativar notas que estejam em execução no momento para realce teclado
active_notes = set()
# Desenhar notas
for start, note, duration in notes:
# Tempo relativo da nota com relação ao tempo atual
t = current_time - start
if 0 <= t <= duration + (HEIGHT / NOTE_SPEED):
# Calcular o X da nota, alinhado com a tecla branca (usando largura das brancas)
if is_black_key(note):
x = white_key_index(note) * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = white_key_index(note) * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
# Calcular posição vertical da nota: começa acima da tela e desce para o teclado
# Quando t=0, y está acima (y=-altura_da_nota), quando t cresce, y sobe até o teclado HEIGHT - PIANO_HEIGHT
y = - (t * NOTE_SPEED) + HEIGHT - PIANO_HEIGHT
# Altura da nota proporcional à duração (limitada)
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration * NOTE_SPEED))
if y + h >= 0 and y <= HEIGHT - PIANO_HEIGHT:
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
# Se a nota está tocando (t dentro duração), destacar tecla
if 0 <= t <= duration:
active_notes.add(note)
# Desenhar teclado no rodapé com teclas ativadas
draw_piano(active_notes)
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
Como funciona:
Notas caem verticalmente: A posição Y é calculada para começar acima da tela (y < 0) e descer para o teclado fixo no rodapé (y = HEIGHT - PIANO_HEIGHT).
Posição horizontal alinhada ao teclado: Cada nota está na horizontal exatamente alinhada com a tecla correspondente do piano.
Duração das notas desenhada como altura dos retângulos: Notas mais longas são blocos mais altos.
Teclado desenhado estático: Branco e preto, teclas são "iluminadas" enquanto a nota está tocando.
Velocidade da animação controlada pela variável NOTE_SPEED em pixels por segundo, pode ser ajustada para casar com o tempo da música.
Como executar:
Instale bibliotecas se não tiver:
code
pip install mido pygame python-rtmidi
Coloque um arquivo MIDI exemplo.mid na mesma pasta.
Rode o script normalmente:
code
python seu_script.py
Se quiser, posso ajudar a:
Integrar controles de pausa/play
Receber entrada MIDI em tempo real
Tornar a velocidade de descida dinâmica conforme BPM do mid
Exportar vídeo da visualização
Melhorar visual estética (cores, efeitos, etc)
Quer avançar com alguma dessas ideias?
Código completo simplificado com nota descendo
python
import mido
import pygame
import sys
WIDTH, HEIGHT = 800, 600
PIANO_HEIGHT = 100
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
FIRST_MIDI_NOTE = 21
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Visualizador MIDI notas descendentes")
clock = pygame.time.Clock()
midi_file = mido.MidiFile('exemplo.mid')
notes = []
time_elapsed = 0.0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
note_on_times[msg.note] = time_elapsed
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times:
start = note_on_times[msg.note]
duration = time_elapsed - start
notes.append((start, msg.note, duration))
del note_on_times[msg.note]
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
def is_black_key(note):
return ((note - FIRST_MIDI_NOTE) % 12) in BLACK_KEY_INDICES
def white_key_index(note):
count = 0
for n in range(FIRST_MIDI_NOTE, note):
if not is_black_key(n):
count += 1
return count
def draw_piano(active_notes):
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
color = (255, 255, 255)
if n in active_notes:
color = (255, 230, 180)
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
color = (0, 0, 0)
if n in active_notes:
color = (255, 100, 100)
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
NOTE_SPEED = 200 # pixels por segundo
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
start_ticks = pygame.time.get_ticks()
running = True
while running:
screen.fill((0, 0, 0))
current_time = (pygame.time.get_ticks() - start_ticks) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
active_notes = set()
for start, note, duration in notes:
t = current_time - start
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration * NOTE_SPEED))
y = t * NOTE_SPEED - h
if 0 <= y <= HEIGHT - PIANO_HEIGHT:
if is_black_key(note):
x = white_key_index(note) * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = white_key_index(note) * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
if 0 <= t <= duration:
active_notes.add(note)
draw_piano(active_notes)
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
Teste esse código e veja as notas descendo verticalmente para o piano, com o teclado iluminando as teclas ativas.
Se quiser, posso ajudar a:
Ajustar velocidade baseada no BPM real do MIDI
Mostrar o progresso da música
Controlar pausar/reiniciar
Outras melhorias visuais
Fique à vontade para perguntar!
import mido
import pygame
import sys
WIDTH, HEIGHT = 800, 600
PIANO_HEIGHT = 100
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
FIRST_MIDI_NOTE = 21
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Visualizador MIDI avançado")
clock = pygame.time.Clock()
midi_file = mido.MidiFile('exemplo.mid')
# Buscar primeiro set_tempo para extrair BPM
tempo_bpm = 120 # Valor padrão
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
# Ler eventos note_on/ note_off com duração
notes = []
time_elapsed = 0.0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
note_on_times[msg.note] = time_elapsed
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times:
start = note_on_times[msg.note]
duration = time_elapsed - start
notes.append((start, msg.note, duration))
del note_on_times[msg.note]
# Total duração aproximada da música
total_duration = midi_file.length
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
def is_black_key(note):
return ((note - FIRST_MIDI_NOTE) % 12) in BLACK_KEY_INDICES
def white_key_index(note):
count = 0
for n in range(FIRST_MIDI_NOTE, note):
if not is_black_key(n):
count += 1
return count
def draw_piano(active_notes):
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
color = (255, 255, 255)
if n in active_notes:
color = (255, 230, 180)
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
color = (0, 0, 0)
if n in active_notes:
color = (255, 100, 100)
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
# Ajustar velocidade para que as notas desçam o total da área visível na duração da música
NOTE_SPEED = (HEIGHT - PIANO_HEIGHT) / total_duration
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0 # tempo total pausado acumulado
running = True
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not paused:
# Pausa: guarda o tempo atual e para o relógio
pause_start_time = pygame.time.get_ticks()
paused = True
else:
# Resumir: acumula o tempo pausado e retoma
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
elif event.key == pygame.K_r:
# Reiniciar o tempo
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
active_notes = set()
for start, note, duration in notes:
t = current_time - start
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration * NOTE_SPEED))
y = t * NOTE_SPEED - h
if 0 <= y <= HEIGHT - PIANO_HEIGHT:
if is_black_key(note):
x = white_key_index(note) * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = white_key_index(note) * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
if 0 <= t <= duration:
active_notes.add(note)
draw_piano(active_notes)
# Desenhar progresso simples na barra no topo
progress = min(max(current_time / total_duration, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
O que foi adicionado?
Leitura dinâmica do BPM e cálculo da velocidade (NOTE_SPEED) para que o total da área (altura da janela menos teclado) seja percorrida no tempo da música.
Barra fina azul no topo indicando progresso da música.
Controles:
Espaço: pausar / continuar
R: reiniciar a música do começo
Para usar
Coloque seu arquivo exemplo.mid na pasta.
Rode o script.
Aperte espaço para pausar e voltar.
Aperte r para reiniciar.
Se quiser, posso ajudar a implementar:
Entrada MIDI ao vivo (piano real)
Mais efeitos visuais (sombras, partículas...)
Exportar visualização para vídeo ou imagens
Fico à disposição para ajudar nos próximos passos!
Passo 3: Ajustar intervalo da área visível (do topo até antes do teclado)
python
visible_height = HEIGHT - PIANO_HEIGHT
# y cresce de 0 (topo) até visible_height (teclado)
Exemplo mínimo do trecho ajustado para o cálculo Y das notas
python
PREROLL = 3.0 # segundos
visible_height = HEIGHT - PIANO_HEIGHT
for start, note, duration in notes:
time_since_appear = current_time - (start - PREROLL)
if 0 <= time_since_appear <= PREROLL:
y = time_since_appear / PREROLL * visible_height
# definir w,h da nota, assim como cor e x
# desenhar retângulo na posição (x, y)
elif time_since_appear > PREROLL and time_since_appear <= PREROLL + duration:
# Nota sendo "tocada" no teclado - pode destacar a tecla correspondente
Código completo com sincronia e preroll (notas descendo chegando no tempo certo):
python
import mido
import pygame
import sys
WIDTH, HEIGHT = 800, 600
PIANO_HEIGHT = 100
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
FIRST_MIDI_NOTE = 21
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Visualizador MIDI sincronia com preroll")
clock = pygame.time.Clock()
midi_file = mido.MidiFile('exemplo.mid')
tempo_bpm = 120 # padrão
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
notes = []
time_elapsed = 0.0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
note_on_times[msg.note] = time_elapsed
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times:
start = note_on_times[msg.note]
duration = time_elapsed - start
notes.append((start, msg.note, duration))
del note_on_times[msg.note]
total_duration = midi_file.length
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
def is_black_key(note):
return ((note - FIRST_MIDI_NOTE) % 12) in BLACK_KEY_INDICES
def white_key_index(note):
count = 0
for n in range(FIRST_MIDI_NOTE, note):
if not is_black_key(n):
count += 1
return count
def draw_piano(active_notes):
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
color = (255, 255, 255)
if n in active_notes:
color = (255, 230, 180)
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
color = (0, 0, 0)
if n in active_notes:
color = (255, 100, 100)
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
PREROLL = 3.0 # segundos que a nota leva para descer do topo até o teclado
visible_height = HEIGHT - PIANO_HEIGHT
paused = False
start_ticks = pygame.time.get_ticks()
pause_start_time = 0
time_paused_accum = 0
running = True
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
active_notes = set()
for start, note, duration in notes:
time_since_appear = current_time - (start - PREROLL)
if 0 <= time_since_appear <= PREROLL:
y = (time_since_appear / PREROLL) * visible_height
# pode adaptar a altura da nota proporcional à duração
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, (duration / PREROLL) * visible_height))
if is_black_key(note):
x = white_key_index(note) * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = white_key_index(note) * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
elif PREROLL < time_since_appear <= PREROLL + duration:
active_notes.add(note)
draw_piano(active_notes)
progress = min(max(current_time / total_duration, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
Como funciona essa abordagem:
A nota surge no topo da área visível PREROLL segundos antes dela chegar ao tempo real de toque.
Ela vai descendo suavemente e chega ao teclado exatamente no momento do start da nota.
O teclado embaixo destaca a tecla enquanto a nota está sendo tocada.
Você pode controlar pausa/comando e ver o progresso visual.
Se quiser, posso ajudar a:
Ajustar o valor do preroll para ficar confortável visualmente
Fazer o cálculo dinâmico da velocidade baseado no BPM e compasso
Sincronizar com entrada MIDI ao vivo para tocar de verdade
Exportar vídeo ou imagens da visualização
Fique à vontade para perguntar! Quer testar esse código? Posso ajudar com mais explicações ou melhorias.
Código final atualizado
python
import mido
import pygame
import sys
WIDTH, HEIGHT = 800, 600
PIANO_HEIGHT = 100
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
FIRST_MIDI_NOTE = 21
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Visualizador MIDI com preroll sincronia e animação")
clock = pygame.time.Clock()
midi_file = mido.MidiFile('exemplo.mid')
# Extrair BPM
tempo_bpm = 120
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
notes = []
time_elapsed = 0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
note_on_times[msg.note] = time_elapsed
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times:
start = note_on_times[msg.note]
duration = time_elapsed - start
notes.append((start, msg.note, duration))
del note_on_times[msg.note]
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
def is_black_key(note):
return ((note - FIRST_MIDI_NOTE) % 12) in BLACK_KEY_INDICES
def white_key_index(note):
count = 0
for n in range(FIRST_MIDI_NOTE, note):
if not is_black_key(n):
count += 1
return count
def lerp(a, b, t):
return a + (b - a) * t
def draw_piano(active_notes, anim_states):
# anim_states: dict {note: tempo_restante_de_animacao}
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
base_color = (255, 255, 255)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
# brilho pulsante usando seno ou interpolação
intensity = lerp(0.5, 1.0, abs((t*10) % 1 - 0.5)*2) # pulso rápido
color = (int(255*intensity), int(230*intensity), int(180*intensity))
else:
color = (255, 230, 180)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
base_color = (0, 0, 0)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.3, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(100*intensity), int(100*intensity))
else:
color = (255, 100, 100)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
PREROLL = 3.0 # segundos de antecipação para a nota iniciar descendo
visible_height = HEIGHT - PIANO_HEIGHT
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
# Velocidade ajustada para sincronizar ponta da nota na tecla em t = start
# Velocidade depende da altura da nota que será calculada individualmente
# Mas como não temos isso antes, usaremos uma velocidade base para área mais altura máxima da nota
# Função para calcular velocidade para uma nota (h) particular
def calc_velocity(h):
return (visible_height + h) / PREROLL
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0
# Animação de toque
ANIM_DURATION = 0.3 # segundos
anim_states = {} # {note: tempo_restante}
running = True
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
anim_states.clear()
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
active_notes = set()
# Atualizar estado das animações
keys_to_delete = []
for k in anim_states:
anim_states[k] -= 1/60
if anim_states[k] <= 0:
keys_to_delete.append(k)
for k in keys_to_delete:
del anim_states[k]
for start, note, duration in notes:
# Altura da nota proporcional à duração
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = calc_velocity(h)
time_since_appear = current_time - (start - PREROLL)
# Nota visível descendo da parte superior até o teclado
if 0 <= time_since_appear <= PREROLL:
y = velocity * time_since_appear - h # movimento descendente, ponta da nota bate na tecla no tempo start
if is_black_key(note):
x = white_key_index(note) * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = white_key_index(note) * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
# Nota está “tocando” no teclado
if start <= current_time <= start + duration:
active_notes.add(note)
# Iniciar animação se não estiver já ativa
if note not in anim_states:
anim_states[note] = ANIM_DURATION
draw_piano(active_notes, anim_states)
progress = min(max(current_time / midi_file.length, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
O que esse código faz
Extrai BPM do MIDI (não altera a velocidade do preroll, mas pode ser usado para futuras melhorias).
Preroll padrão 3 segundos para a nota descer toda a área.
Calcula a velocidade individual para que a ponta da nota encoste na tecla exatamente no tempo da nota começar.
Animação sutil na tecla tocada por 0.3s com brilho pulsante.
Pausa, reinício e barra de progresso implementados.
O que você pode ajustar
Alterar o valor de PREROLL para definir a distância visual para as notas.
Modificar ANIM_DURATION para controlar o tempo do efeito visual da tecla sendo pressionada.
Ajustar cores e tamanhos no draw_piano e desenho das notas.
Integrar cálculo do tempo relativo ao BPM para controlar velocidade e aceleração mais fielmente.
Quer ajuda para isso? Ou para integrar também a parte de áudio (sincronizar som real junto)?
Posso ajudar você a expandir!
import mido
import pygame
import sys
import cv2
import numpy as np
# --- Configurações básicas e MIDI iguais ao código anterior ---
WIDTH, HEIGHT = 800, 600
PIANO_HEIGHT = 100
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
FIRST_MIDI_NOTE = 21
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Visualizador MIDI com background vídeo")
clock = pygame.time.Clock()
midi_file = mido.MidiFile('exemplo.mid')
# [Processar notes e BPM igual ao código anterior, omitido aqui para foco]
# --- Configuração Video Background ---
video_path = "background.mp4" # Caminho do vídeo, altere conforme necessário
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir vídeo: {video_path}")
sys.exit(1)
def get_video_frame():
ret, frame = cap.read()
if not ret:
# Reiniciar vídeo
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = cv2.resize(frame, (WIDTH, HEIGHT))
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame) # Rotacionar, pois pygame e cv2 têm coordenadas diferentes
frame = pygame.surfarray.make_surface(frame)
return frame
# --- Controle de Velocidade ---
speed_multiplier = 1.0
speed_step = 0.1 # Quanto a velocidade aumenta/diminui ao usar teclado
PREROLL = 3.0
# [Demais variáveis do código anterior para notas, piano, animação, etc]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
# Controle velocidade com + e -
if event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
speed_multiplier += speed_step
print(f"Velocidade aumentada para {speed_multiplier:.2f}")
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
speed_multiplier = max(0.1, speed_multiplier - speed_step)
print(f"Velocidade reduzida para {speed_multiplier:.2f}")
# Outros controles pausa, restart (igual anterior), etc...
# --- Desenho do background do vídeo ---
frame_surface = get_video_frame()
screen.blit(frame_surface, (0, 0))
# --- Calcular current_time, pausas, atualizar notas igual antes ---
# --- Desenhar notas com velocidade ajustada ---
# velocidade base calculada mais multiplicador:
# Exemplo:
# velocity = calc_velocity(h) * speed_multiplier
# [Aqui insira o loop para desenhar notas, teclado, animacoes com a nova velocity]
pygame.display.flip()
clock.tick(60)
cap.release()
pygame.quit()
sys.exit()
Comentários importantes
O vídeo fica desenhado antes das notas e teclado (screen.blit(frame_surface, (0, 0))).
A função get_video_frame lê frame a frame, reiniciando quando acaba.
Para evitar lag, certifique-se que o vídeo tenha resolução compatível (800x600 recomendado).
Ajuste o speed_multiplier no jogo para acelerar ou desacelerar as notas na tela.
Atenção: keyboard input usa algumas variações, K_EQUALS pode ser a tecla “+” (Shift + “=”) ou apenas “=”, teste o que funciona no seu teclado.
Próximos passos
Quer o código completo integrado e testado para te entregar? Posso preparar uma versão com:
Todo o código de leitura MIDI, notas descendo sincronizadas com preroll.
Controle de velocidade funcionando (teclas + e -).
Vídeo background carregado pela OpenCV.
Animação do piano e notas em cima do vídeo.
Só avisar! Se preferir, também incluo:
Opção para carregar vídeo de fundo via linha de comando ou GUI
Ajuste fino de parâmetros do visualizador em runtime
Fico à disposição para ajudar a montar tudo isso! Quer?
import mido
import pygame
import sys
import cv2
import numpy as np
# Configurações básicas da janela
WIDTH, HEIGHT = 800, 600
PIANO_HEIGHT = 100
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
FIRST_MIDI_NOTE = 21
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("MIDI Visualizer com Vídeo Background")
clock = pygame.time.Clock()
# Carregue seu arquivo MIDI - altere o nome conforme o seu arquivo
midi_filename = "exemplo.mid"
midi_file = mido.MidiFile(midi_filename)
# Extração do BPM (usamos o primeiro set_tempo, se houver)
tempo_bpm = 120
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
# Processar eventos de notas para obter start time e duração
notes = []
time_elapsed = 0.0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
note_on_times[msg.note] = time_elapsed
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times:
start = note_on_times[msg.note]
duration = time_elapsed - start
notes.append((start, msg.note, duration))
del note_on_times[msg.note]
# vídeo background via OpenCV
video_path = "background.mp4" # Altere para seu vídeo
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir vídeo: {video_path}")
sys.exit(1)
def get_video_frame():
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = cv2.resize(frame, (WIDTH, HEIGHT))
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
surface = pygame.surfarray.make_surface(frame)
return surface
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
def is_black_key(note):
return ((note - FIRST_MIDI_NOTE) % 12) in BLACK_KEY_INDICES
def white_key_index(note):
count = 0
for n in range(FIRST_MIDI_NOTE, note):
if not is_black_key(n):
count += 1
return count
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
PREROLL = 3.0 # Tempo em segundos que a nota leva para descer toda a área visível
visible_height = HEIGHT - PIANO_HEIGHT
ANIM_DURATION = 0.3 # duração do efeito de tecla pressionada
# Função linear de interpolação para animação
def lerp(a, b, t):
return a + (b - a) * t
def draw_piano(active_notes, anim_states):
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
base_color = (255, 255, 255)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.5, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(230*intensity), int(180*intensity))
else:
color = (255, 230, 180)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
base_color = (0, 0, 0)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.3, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(100*intensity), int(100*intensity))
else:
color = (255, 100, 100)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
# Função para calcular velocidade para uma nota de altura h
def calc_velocity(h):
return (visible_height + h) / PREROLL
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0
speed_multiplier = 1.0
speed_step = 0.1
anim_states = {}
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_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
anim_states.clear()
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
speed_multiplier += speed_step
print(f"Velocidade aumentada para {speed_multiplier:.2f}")
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
speed_multiplier = max(0.1, speed_multiplier - speed_step)
print(f"Velocidade reduzida para {speed_multiplier:.2f}")
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
# --- Desenhar o vídeo no background ---
video_frame = get_video_frame()
screen.blit(video_frame, (0, 0))
active_notes = set()
# Atualizar animações de brilho nas teclas
keys_to_delete = []
for k in anim_states:
anim_states[k] -= 1/60
if anim_states[k] <= 0:
keys_to_delete.append(k)
for k in keys_to_delete:
del anim_states[k]
for start, note, duration in notes:
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = calc_velocity(h) * speed_multiplier
time_since_appear = current_time - (start - PREROLL / speed_multiplier) # ajustar preroll pela velocidade
if 0 <= time_since_appear <= PREROLL / speed_multiplier:
y = velocity * time_since_appear - h
if is_black_key(note):
x = white_key_index(note) * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = white_key_index(note) * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
if start <= current_time <= start + duration:
active_notes.add(note)
if note not in anim_states:
anim_states[note] = ANIM_DURATION
# Desenha o piano e teclas com animação
draw_piano(active_notes, anim_states)
# Barra de progresso simples
progress = min(max(current_time / midi_file.length, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
clock.tick(60)
cap.release()
pygame.quit()
sys.exit()
Como usar:
Troque "exemplo.mid" e "background.mp4" para seus arquivos.
Use + e - para controlar velocidade das notas.
Pressione space para pausar/resumir.
Pressione r para reiniciar visualização.
O vídeo aparece no background e as notas + piano ficam no foreground, visíveis e animados.
Se quiser, posso ajudar a melhorar mais (ex: pause visual, progressão mais detalhada, playlists, ou integração com áudio).
Só avisar!
import mido
import pygame
import sys
import cv2
import numpy as np
# ---- Configurações principais ----
WIDTH, HEIGHT = 800, 600
PIANO_HEIGHT = 100
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
FIRST_MIDI_NOTE = 21
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("MIDI Visualizer com Vídeo Background (Letterbox)")
clock = pygame.time.Clock()
# --- Função para manter proporção com letterbox ---
def resize_with_letterbox(frame, target_width, target_height):
h, w = frame.shape[:2]
scale = min(target_width / w, target_height / h)
new_w = int(w * scale)
new_h = int(h * scale)
resized_frame = cv2.resize(frame, (new_w, new_h))
# Fundo preto
canvas = np.zeros((target_height, target_width, 3), dtype=np.uint8)
# Centro
x_offset = (target_width - new_w) // 2
y_offset = (target_height - new_h) // 2
canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized_frame
return canvas
# --- Vídeo background ---
video_path = "background.mp4"
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir vídeo: {video_path}")
sys.exit(1)
def get_video_frame():
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = resize_with_letterbox(frame, WIDTH, HEIGHT)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
surface = pygame.surfarray.make_surface(frame)
return surface
# --- MIDI ---
midi_filename = "exemplo.mid"
midi_file = mido.MidiFile(midi_filename)
tempo_bpm = 120
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
notes = []
time_elapsed = 0.0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
note_on_times[msg.note] = time_elapsed
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times:
start = note_on_times[msg.note]
duration = time_elapsed - start
notes.append((start, msg.note, duration))
del note_on_times[msg.note]
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
def is_black_key(note):
return ((note - FIRST_MIDI_NOTE) % 12) in BLACK_KEY_INDICES
def white_key_index(note):
count = 0
for n in range(FIRST_MIDI_NOTE, note):
if not is_black_key(n):
count += 1
return count
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
PREROLL = 3.0
visible_height = HEIGHT - PIANO_HEIGHT
ANIM_DURATION = 0.3
def lerp(a, b, t):
return a + (b - a) * t
def draw_piano(active_notes, anim_states):
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
base_color = (255, 255, 255)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.5, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(230*intensity), int(180*intensity))
else:
color = (255, 230, 180)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
base_color = (0, 0, 0)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.3, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(100*intensity), int(100*intensity))
else:
color = (255, 100, 100)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
def calc_velocity(h):
return (visible_height + h) / PREROLL
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0
speed_multiplier = 1.0
speed_step = 0.1
anim_states = {}
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_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
anim_states.clear()
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
speed_multiplier += speed_step
print(f"Velocidade aumentada para {speed_multiplier:.2f}")
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
speed_multiplier = max(0.1, speed_multiplier - speed_step)
print(f"Velocidade reduzida para {speed_multiplier:.2f}")
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
# --- Desenhar vídeo no background ---
video_frame = get_video_frame()
screen.blit(video_frame, (0, 0))
active_notes = set()
keys_to_delete = []
for k in anim_states:
anim_states[k] -= 1/60
if anim_states[k] <= 0:
keys_to_delete.append(k)
for k in keys_to_delete:
del anim_states[k]
for start, note, duration in notes:
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = calc_velocity(h) * speed_multiplier
time_since_appear = current_time - (start - PREROLL / speed_multiplier)
if 0 <= time_since_appear <= PREROLL / speed_multiplier:
y = velocity * time_since_appear - h
if is_black_key(note):
x = white_key_index(note) * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = white_key_index(note) * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
if start <= current_time <= start + duration:
active_notes.add(note)
if note not in anim_states:
anim_states[note] = ANIM_DURATION
draw_piano(active_notes, anim_states)
# Barra de progresso
progress = min(max(current_time / midi_file.length, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
clock.tick(60)
cap.release()
pygame.quit()
sys.exit()
O que mudou?
A função resize_with_letterbox() garante o vídeo fica redimensionado respeitando a proporção, com bars pretas nas bordas se necessário.
A cada frame, o vídeo é redimensionado assim antes de ser desenhado (mantendo o aspecto).
O draw do vídeo é feito primeiro (screen.blit(video_frame, (0, 0))).
Depois desenhamos notas e o piano com animações normalmente no foreground.
Controle de velocidade ajusta a velocidade dinamicamente de todas as notas.
Teclas space para pausar, r para reiniciar, +/- para alterar velocidade.
Teste o código, e me avise para ajudar a melhorar ou ajustar algum ponto.
Se quiser posso ajudar a:
Incluir interface para carregar arquivos MIDI/vídeo
Controle de velocidade video_speed, pulando frames conforme o valor.
Função get_video_frame_controlled(delta_time) que gerencia quando e quantos frames ler.
Guarda o último frame para não avancar se pausado ou se o delta_time for pequeno.
Sincronização do estado pausa vídeo com pausa da visualização.
Quer que eu te integre essas mudanças no código completo para rodar direto?
import mido
import pygame
import sys
import cv2
import numpy as np
# --- Constantes iniciais fixas ---
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
FIRST_MIDI_NOTE = 21
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
ANIM_DURATION = 0.3
PREROLL = 3.0 # segundos
# --- Configurações iniciais da janela ---
INITIAL_WIDTH, INITIAL_HEIGHT = 800, 600
PIANO_HEIGHT_RATIO = 0.15 # piano como proporção da altura da janela
pygame.init()
screen = pygame.display.set_mode((INITIAL_WIDTH, INITIAL_HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("MIDI Visualizer com Controle de Vídeo Avançado")
clock = pygame.time.Clock()
# --- Função para manter proporção com letterbox ---
def resize_with_letterbox(frame, target_width, target_height):
h, w = frame.shape[:2]
scale = min(target_width / w, target_height / h)
new_w = int(w * scale)
new_h = int(h * scale)
resized_frame = cv2.resize(frame, (new_w, new_h))
canvas = np.zeros((target_height, target_width, 3), dtype=np.uint8)
x_offset = (target_width - new_w) // 2
y_offset = (target_height - new_h) // 2
canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized_frame
return canvas
# --- Carregar vídeo ---
video_path = "background.mp4"
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir vídeo: {video_path}")
sys.exit(1)
# Variáveis de controle do vídeo
video_paused = False
video_speed = 1.0 # 1.0 = normal
video_frame_time_accum = 0.0
video_fps = cap.get(cv2.CAP_PROP_FPS) or 30 # detectar fps do vídeo
current_video_surface = None # último frame exibido
def get_video_frame_controlled(delta_time, width, height):
global video_frame_time_accum, video_paused, current_video_surface, cap, video_fps
if video_paused:
return current_video_surface # mantém frame atual
video_frame_time_accum += delta_time * video_speed
frames_to_advance = int(video_frame_time_accum * video_fps)
if frames_to_advance >= 1:
video_frame_time_accum -= frames_to_advance / video_fps
# pular frames para manter velocidade
for _ in range(frames_to_advance -1):
ret = cap.grab()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = resize_with_letterbox(frame, width, height)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
current_video_surface = pygame.surfarray.make_surface(frame)
return current_video_surface
# --- Carregar MIDI ---
midi_filename = "exemplo.mid"
midi_file = mido.MidiFile(midi_filename)
tempo_bpm = 120
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
notes = []
time_elapsed = 0.0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
note_on_times[msg.note] = time_elapsed
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times:
start = note_on_times[msg.note]
duration = time_elapsed - start
notes.append((start, msg.note, duration))
del note_on_times[msg.note]
# --- Variáveis dinâmicas que serão recalculadas em resize ---
WIDTH, HEIGHT = INITIAL_WIDTH, INITIAL_HEIGHT
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT
def is_black_key(note):
return ((note - FIRST_MIDI_NOTE) % 12) in BLACK_KEY_INDICES
def white_key_index(note):
count = 0
for n in range(FIRST_MIDI_NOTE, note):
if not is_black_key(n):
count += 1
return count
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
def lerp(a, b, t):
return a + (b - a) * t
def draw_piano(active_notes, anim_states):
global white_key_width, white_key_height, black_key_width, black_key_height
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
base_color = (255, 255, 255)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.5, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(230*intensity), int(180*intensity))
else:
color = (255, 230, 180)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(FIRST_MIDI_NOTE, FIRST_MIDI_NOTE + NUM_KEYS):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
base_color = (0, 0, 0)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.3, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(100*intensity), int(100*intensity))
else:
color = (255, 100, 100)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
def calc_velocity(h):
global visible_height
return (visible_height + h) / PREROLL
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0
speed_multiplier = 1.0
speed_step = 0.1
anim_states = {}
running = True
while running:
delta_time = clock.tick(60) / 1000.0 # tempo em segundos desde último frame
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.VIDEORESIZE:
WIDTH, HEIGHT = event.w, event.h
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
# Recalcular dimensões dependentes
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
video_paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
video_paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
video_paused = False
anim_states.clear()
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
video_frame_time_accum = 0.0
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
speed_multiplier += speed_step
print(f"Velocidade notas aumentada para {speed_multiplier:.2f}")
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
speed_multiplier = max(0.1, speed_multiplier - speed_step)
print(f"Velocidade notas reduzida para {speed_multiplier:.2f}")
elif event.key == pygame.K_LEFTBRACKET:
video_speed = max(0.1, video_speed - 0.1)
print(f"Velocidade vídeo reduzida para {video_speed:.2f}")
elif event.key == pygame.K_RIGHTBRACKET:
video_speed += 0.1
print(f"Velocidade vídeo aumentada para {video_speed:.2f}")
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
# --- Atualizar e desenhar frame do vídeo com controle ---
current_video_surface = get_video_frame_controlled(delta_time, WIDTH, HEIGHT)
if current_video_surface:
screen.blit(current_video_surface, (0, 0))
else:
screen.fill((0, 0, 0)) # fallback: fundo preto
active_notes = set()
keys_to_delete = []
for k in anim_states:
anim_states[k] -= delta_time
if anim_states[k] <= 0:
keys_to_delete.append(k)
for k in keys_to_delete:
del anim_states[k]
for start, note, duration in notes:
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = calc_velocity(h) * speed_multiplier
time_since_appear = current_time - (start - PREROLL / speed_multiplier)
if 0 <= time_since_appear <= PREROLL / speed_multiplier:
y = velocity * time_since_appear - h
if is_black_key(note):
x = white_key_index(note) * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = white_key_index(note) * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
if start <= current_time <= start + duration:
active_notes.add(note)
if note not in anim_states:
anim_states[note] = ANIM_DURATION
draw_piano(active_notes, anim_states)
# Barra progresso
progress = min(max(current_time / midi_file.length, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
cap.release()
pygame.quit()
sys.exit()
Resumo dos novos controles:
space: pausa/resume visualização + vídeo
r: reinicia visualização + vídeo
+ / -: aumenta/diminui velocidade das notas
[ / ]: diminui/aumenta velocidade do vídeo (frames pulados)
Assim o vídeo e o visualizador MIDI ficam sincronizados e você controla playback, velocidade do vídeo e das notas.
Se precisar de ajuda para funcionalidades adicionais ou integração com áudio, me avise!
Use sempre esta variável para validações e para o desenho.
4) Revisão rápida da função white_key_index para não quebrar com notas inválidas
Se você preferir, pode proteger:
python
def white_key_index(note):
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
return None
count = 0
for n in range(MIN_VISIBLE_NOTE, note):
if not is_black_key(n):
count += 1
return count
E ao usar essa função:
python
idx = white_key_index(note)
if idx is None:
continue
Resumo do ajuste
Para corrigir a exibição de notas erradas ou “fantasmas”:
Filtre NOTAS fora do intervalo MIDI que seu visualizador suporta no momento da leitura.
Proteja cálculos de posição para não usar notas inválidas.
Isso vai garantir que somente notas do arquivo MIDI e que estejam dentro do teclado aparecem.
Quer que eu faça essas correções diretas no seu código completo e te envie a versão atualizada?
import mido
import pygame
import sys
import cv2
import numpy as np
# --- Constantes e configurações ---
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
MIN_VISIBLE_NOTE = 21
MAX_VISIBLE_NOTE = 108
FIRST_MIDI_NOTE = MIN_VISIBLE_NOTE
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
ANIM_DURATION = 0.3
PREROLL = 3.0 # segundos
INITIAL_WIDTH, INITIAL_HEIGHT = 800, 600
PIANO_HEIGHT_RATIO = 0.15 # piano como proporção da altura da janela
pygame.init()
screen = pygame.display.set_mode((INITIAL_WIDTH, INITIAL_HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("MIDI Visualizer — Notas filtradas pelo range")
clock = pygame.time.Clock()
def resize_with_letterbox(frame, target_width, target_height):
h, w = frame.shape[:2]
scale = min(target_width / w, target_height / h)
new_w = int(w * scale)
new_h = int(h * scale)
resized_frame = cv2.resize(frame, (new_w, new_h))
canvas = np.zeros((target_height, target_width, 3), dtype=np.uint8)
x_offset = (target_width - new_w) // 2
y_offset = (target_height - new_h) // 2
canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized_frame
return canvas
video_path = "background.mp4"
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir vídeo: {video_path}")
sys.exit(1)
video_paused = False
video_speed = 1.0
video_frame_time_accum = 0.0
video_fps = cap.get(cv2.CAP_PROP_FPS) or 30
current_video_surface = None
def get_video_frame_controlled(delta_time, width, height):
global video_frame_time_accum, video_paused, current_video_surface, cap, video_fps
if video_paused:
return current_video_surface
video_frame_time_accum += delta_time * video_speed
frames_to_advance = int(video_frame_time_accum * video_fps)
if frames_to_advance >= 1:
video_frame_time_accum -= frames_to_advance / video_fps
for _ in range(frames_to_advance -1):
ret = cap.grab()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = resize_with_letterbox(frame, width, height)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
current_video_surface = pygame.surfarray.make_surface(frame)
return current_video_surface
midi_filename = "exemplo.mid"
midi_file = mido.MidiFile(midi_filename)
tempo_bpm = 120
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
notes = []
time_elapsed = 0.0
note_on_times = {}
# FILTRANDO notas fora do intervalo 21 a 108 aqui
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
if MIN_VISIBLE_NOTE <= msg.note <= MAX_VISIBLE_NOTE:
note_on_times[msg.note] = time_elapsed
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times:
if MIN_VISIBLE_NOTE <= msg.note <= MAX_VISIBLE_NOTE:
start = note_on_times[msg.note]
duration = time_elapsed - start
notes.append((start, msg.note, duration))
del note_on_times[msg.note]
WIDTH, HEIGHT = INITIAL_WIDTH, INITIAL_HEIGHT
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT
def is_black_key(note):
return ((note - FIRST_MIDI_NOTE) % 12) in BLACK_KEY_INDICES
def white_key_index(note):
if note < MIN_VISIBLE_NOTE or note > MAX_VISIBLE_NOTE:
return None
count = 0
for n in range(MIN_VISIBLE_NOTE, note):
if not is_black_key(n):
count += 1
return count
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
def lerp(a, b, t):
return a + (b - a) * t
def draw_piano(active_notes, anim_states):
global white_key_width, white_key_height, black_key_width, black_key_height
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
base_color = (255, 255, 255)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.5, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(230*intensity), int(180*intensity))
else:
color = (255, 230, 180)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
base_color = (0, 0, 0)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.3, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(100*intensity), int(100*intensity))
else:
color = (255, 100, 100)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
def calc_velocity(h):
global visible_height
return (visible_height + h) / PREROLL
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0
speed_multiplier = 1.0
speed_step = 0.1
anim_states = {}
running = True
while running:
delta_time = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.VIDEORESIZE:
WIDTH, HEIGHT = event.w, event.h
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
# Atualização das variáveis espaciais
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
video_paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
video_paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
video_paused = False
anim_states.clear()
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
video_frame_time_accum = 0.0
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
speed_multiplier += speed_step
print(f"Velocidade notas aumentada para {speed_multiplier:.2f}")
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
speed_multiplier = max(0.1, speed_multiplier - speed_step)
print(f"Velocidade notas reduzida para {speed_multiplier:.2f}")
elif event.key == pygame.K_LEFTBRACKET:
video_speed = max(0.1, video_speed - 0.1)
print(f"Velocidade vídeo reduzida para {video_speed:.2f}")
elif event.key == pygame.K_RIGHTBRACKET:
video_speed += 0.1
print(f"Velocidade vídeo aumentada para {video_speed:.2f}")
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
current_video_surface = get_video_frame_controlled(delta_time, WIDTH, HEIGHT)
if current_video_surface:
screen.blit(current_video_surface, (0, 0))
else:
screen.fill((0, 0, 0))
active_notes = set()
keys_to_delete = []
for k in anim_states:
anim_states[k] -= delta_time
if anim_states[k] <= 0:
keys_to_delete.append(k)
for k in keys_to_delete:
del anim_states[k]
for start, note, duration in notes:
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
continue # Extra proteção
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = calc_velocity(h) * speed_multiplier
time_since_appear = current_time - (start - PREROLL / speed_multiplier)
if 0 <= time_since_appear <= PREROLL / speed_multiplier:
y = velocity * time_since_appear - h
idx = white_key_index(note)
if idx is None:
continue
if is_black_key(note):
x = idx * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = idx * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
if start <= current_time <= start + duration:
active_notes.add(note)
if note not in anim_states:
anim_states[note] = ANIM_DURATION
draw_piano(active_notes, anim_states)
progress = min(max(current_time / midi_file.length, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
cap.release()
pygame.quit()
sys.exit()
Resumo
Agora só considera notas no intervalo padrão 21 a 108.
O filtro é aplicado na leitura e confirmado na renderização.
Função white_key_index é protegida para notas fora do intervalo.
Qualquer nota fora do range é ignorada para evitar "notas fantasmas".
Continua com janela redimensionável, controle avançado do vídeo e da velocidade.
Se precisar de mais alguma melhoria ou funcionalidade, vamos em frente!
Exemplo:
python
if msg.channel == canal_desejado:
# processa a nota
4) Notas duplicadas por múltiplos eventos simultâneos
Se seu MIDI tem eventos repetidos (ex: notas ligadas novamente antes de desligar), certifique-se de que seu código não duplique notas:
Ignore note_on se a mesma nota já estiver ativa.
Ou permita gleiche nota abrindo sua duração até o próximo note_off.
5) Verifique o arquivo MIDI
Use um visualizador MIDI (ex: MidiEditor, MuseScore) para confirmar exatamente as notas e o tempo.
Isso garante que seu teste é correto.
Código aprimorado para lidar com notas abertas corretamente
Vou mostrar como adaptar a leitura dos eventos para garantir que cada nota tem duração correta, e que nenhuma nota extra fica aberta.
python
notes = []
time_elapsed = 0.0
note_on_times = {} # {note: [list_of_start_times]} para lidar com notas que se sobrepõem
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
if MIN_VISIBLE_NOTE <= msg.note <= MAX_VISIBLE_NOTE:
# push start time para nota. Algumas vezes, várias ocorrências podem acontecer sobrepostas
note_on_times.setdefault(msg.note, []).append(time_elapsed)
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times and note_on_times[msg.note]:
start_time = note_on_times[msg.note].pop(0) # remove a primeira ocorrência
if MIN_VISIBLE_NOTE <= msg.note <= MAX_VISIBLE_NOTE:
duration = time_elapsed - start_time
if duration < 0: # proteção
duration = 0.01
notes.append((start_time, msg.note, duration))
# Após ler todos os eventos, fechar notas abertas no fim da música
end_time = midi_file.length
for note, start_times in note_on_times.items():
for start_time in start_times:
duration = end_time - start_time
if duration < 0:
duration = 0.01
notes.append((start_time, note, duration))
Assim, seu visualizador vai processar corretamente cada início e fim das notas e evitará que notas apareçam sem estar presentes no MIDI.
Recapitulando:
Assegure que note_on (velocity>0) e note_off/note_on (velocity=0) sejam tratados corretamente.
Armazene múltiplos eventos note_on para a mesma nota se acontecerem antes do note_off.
Ao receber note_off, emparelhe com o primeiro note_on não finalizado (FIFO).
No fim, feche notas abertas com duração até o fim do arquivo MIDI.
Filtre as notas para ficar dentro do intervalo visível.
Quer que eu integre esse ajuste no seu código completo atual? Isso deve corrigir o problema de notas extras e garantir que o visual exibirá exatamente as notas do seu MIDI, inclusive em acordes como o Dó maior com Dó, Mi e Sol.
import mido
import pygame
import sys
import cv2
import numpy as np
# Configurações do piano e MIDI
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
MIN_VISIBLE_NOTE = 21
MAX_VISIBLE_NOTE = 108
FIRST_MIDI_NOTE = MIN_VISIBLE_NOTE
BLACK_KEY_INDICES = [1, 3, 6, 8, 10]
ANIM_DURATION = 0.3
PREROLL = 3.0 # segundos
# Configuração da janela
INITIAL_WIDTH, INITIAL_HEIGHT = 800, 600
PIANO_HEIGHT_RATIO = 0.15
pygame.init()
screen = pygame.display.set_mode((INITIAL_WIDTH, INITIAL_HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("Visualizador MIDI com notas corretas")
clock = pygame.time.Clock()
def resize_with_letterbox(frame, target_width, target_height):
h, w = frame.shape[:2]
scale = min(target_width / w, target_height / h)
new_w = int(w * scale)
new_h = int(h * scale)
resized_frame = cv2.resize(frame, (new_w, new_h))
canvas = np.zeros((target_height, target_width, 3), dtype=np.uint8)
x_offset = (target_width - new_w) // 2
y_offset = (target_height - new_h) // 2
canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized_frame
return canvas
video_path = "background.mp4"
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir vídeo: {video_path}")
sys.exit(1)
video_paused = False
video_speed = 1.0
video_frame_time_accum = 0.0
video_fps = cap.get(cv2.CAP_PROP_FPS) or 30
current_video_surface = None
def get_video_frame_controlled(delta_time, width, height):
global video_frame_time_accum, video_paused, current_video_surface, cap, video_fps
if video_paused:
return current_video_surface
video_frame_time_accum += delta_time * video_speed
frames_to_advance = int(video_frame_time_accum * video_fps)
if frames_to_advance >= 1:
video_frame_time_accum -= frames_to_advance / video_fps
# pular frames para ajustar velocidade
for _ in range(frames_to_advance -1):
ret = cap.grab()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = resize_with_letterbox(frame, width, height)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
current_video_surface = pygame.surfarray.make_surface(frame)
return current_video_surface
midi_filename = "exemplo.mid"
midi_file = mido.MidiFile(midi_filename)
tempo_bpm = 120
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
# Leitura corrigida para múltiplas ocorrências simultâneas da mesma nota
notes = []
time_elapsed = 0.0
note_on_times = {} # dict: note -> list de tempos de início
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
if MIN_VISIBLE_NOTE <= msg.note <= MAX_VISIBLE_NOTE:
note_on_times.setdefault(msg.note, []).append(time_elapsed)
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times and note_on_times[msg.note]:
start_time = note_on_times[msg.note].pop(0)
duration = time_elapsed - start_time
if duration <= 0:
duration = 0.01
notes.append((start_time, msg.note, duration))
# Fechar notas abertas no final da música
end_time = midi_file.length
for note, start_list in note_on_times.items():
for start_time in start_list:
duration = end_time - start_time
if duration <= 0:
duration = 0.01
notes.append((start_time, note, duration))
WIDTH, HEIGHT = INITIAL_WIDTH, INITIAL_HEIGHT
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT
def is_black_key(note):
return ((note - FIRST_MIDI_NOTE) % 12) in BLACK_KEY_INDICES
def white_key_index(note):
if note < MIN_VISIBLE_NOTE or note > MAX_VISIBLE_NOTE:
return None
count = 0
for n in range(MIN_VISIBLE_NOTE, note):
if not is_black_key(n):
count += 1
return count
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
def lerp(a, b, t):
return a + (b - a) * t
def draw_piano(active_notes, anim_states):
global white_key_width, white_key_height, black_key_width, black_key_height
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
base_color = (255, 255, 255)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.5, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(230*intensity), int(180*intensity))
else:
color = (255, 230, 180)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
base_color = (0, 0, 0)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.3, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(100*intensity), int(100*intensity))
else:
color = (255, 100, 100)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
def calc_velocity(h):
global visible_height
return (visible_height + h) / PREROLL
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0
speed_multiplier = 1.0
speed_step = 0.1
anim_states = {}
running = True
while running:
delta_time = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.VIDEORESIZE:
WIDTH, HEIGHT = event.w, event.h
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
video_paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
video_paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
video_paused = False
anim_states.clear()
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
video_frame_time_accum = 0.0
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
speed_multiplier += speed_step
print(f"Velocidade notas aumentada para {speed_multiplier:.2f}")
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
speed_multiplier = max(0.1, speed_multiplier - speed_step)
print(f"Velocidade notas reduzida para {speed_multiplier:.2f}")
elif event.key == pygame.K_LEFTBRACKET:
video_speed = max(0.1, video_speed - 0.1)
print(f"Velocidade vídeo reduzida para {video_speed:.2f}")
elif event.key == pygame.K_RIGHTBRACKET:
video_speed += 0.1
print(f"Velocidade vídeo aumentada para {video_speed:.2f}")
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
current_video_surface = get_video_frame_controlled(delta_time, WIDTH, HEIGHT)
if current_video_surface:
screen.blit(current_video_surface, (0, 0))
else:
screen.fill((0, 0, 0))
active_notes = set()
keys_to_delete = []
for k in anim_states:
anim_states[k] -= delta_time
if anim_states[k] <= 0:
keys_to_delete.append(k)
for k in keys_to_delete:
del anim_states[k]
for start, note, duration in notes:
# Segurança extra
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
continue
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = calc_velocity(h) * speed_multiplier
time_since_appear = current_time - (start - PREROLL / speed_multiplier)
if 0 <= time_since_appear <= PREROLL / speed_multiplier:
y = velocity * time_since_appear - h
idx = white_key_index(note)
if idx is None:
continue
if is_black_key(note):
x = idx * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = idx * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
if start <= current_time <= start + duration:
active_notes.add(note)
if note not in anim_states:
anim_states[note] = ANIM_DURATION
draw_piano(active_notes, anim_states)
progress = min(max(current_time / midi_file.length, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
cap.release()
pygame.quit()
sys.exit()
Com isso:
Cada nota é corretamente emparelhada entre “note_on” e “note_off”.
Múltiplas ocorrências simultâneas da mesma nota são tratadas.
Só notas dentro do intervalo do piano são exibidas.
Notas "fantasmas" ou extras desaparecem.
Se precisar, posso ajudar também com outras melhorias ou explicações!
Solução:
Confirme que o piano começa na nota midi 21 (A0), que é o padrão.
Se o arquivo MIDI começa com outra nota, adapte MIN_VISIBLE_NOTE para a nota inicial correta.
Ajuste o código para mapear as notas conforme o range do piano.
5) Para evitar dúvidas, aqui está código para imprimir no console todas as notas lidas, para checar seu valor MIDI e horário
Adicione temporariamente:
python
for start, note, duration in notes:
print(f"Nota {note} começa em {start:.2f}s duração {duration:.2f}s")
Isso ajuda saber que notas exatamente estão sendo tocadas.
6) Se quiser transpor as notas para outra tonalidade (exemplo: de C para D), seria uma questão separada
Isso implica adicionar uma constante TRANSPOSITION e somar no valor de note:
python
TRANSPOSITION = 2 # +2 semitons
for start, note, duration in notes:
note += TRANSPOSITION
...
Mas no seu caso, como quer o acorde correto exatamente do arquivo MIDI, NÃO faça nenhuma transposição.
Conclusão: passo a passo para resolver o problema "aparência tonal errada"
Verifique o arquivo MIDI com um visualizador MIDI independente, cheque os números das notas.
Faça um debug/passeio no código imprimindo as notas lidas e confirmando seus valores.
Confirme que o intervalo MIN_VISIBLE_NOTE a MAX_VISIBLE_NOTE cobre todas as notas utilizadas e é consistente com a imagem do teclado.
Confira o cálculo do índice da tecla branca e a posição horizontal para garantir que cada nota vá para a tecla certa.
Evite qualquer alteração ou transposição das notas antes do desenho.
Caso tenha áudio ou outro plugin sincronizado, certifique-se que ele também esteja sem transposição.
Se quiser, posso ajudar a revisar seu arquivo MIDI, ou inserir prints e debug no seu código para rastrear as notas lidas e desenhadas. Ou ajudar ajustar o código para tonalidade/escala correta.
Quer que eu faça isso?
Próximos passos:
Rode o programa no terminal/console com esse debug ligado.
Pegue as notas que aparecem na saída, confirme se elas correspondem ao esperado para seu acorde (ex: para Dó maior, as notas MIDI devem ser 60 = dó, 64 = mi, 67 = sol em canal padrão).
Se alguma nota inesperada aparecer, poderemos ver esse valor e investigar se ela vem do MIDI ou da lógica.
Se quiser, posso ajudar a interpretar essa saída ou até criar filtro para descartar canais/instrumentos que geram essas notas extras.
Quer que eu envie o programa atualizado completo com essas mensagens de log?
Observe na saída as notas que aparecem em tempo próximo do zero para ver se só aparecem as notas 60, 64 e 67.
Se não, seu arquivo MIDI pode conter outras notas ou introduções prévias.
O que fazer para visualizar só uma parte específica (exemplo: só acordes perto do tempo 0)?
Filtrar por intervalo de tempo
Você pode modificar o loop que desenha para só exibir notas cuja start esteja dentro de um intervalo desejado, por exemplo:
python
MIN_TIME = 0.0
MAX_TIME = 5.0 # segundos, ajuste como quiser
for start, note, duration in notes:
if start < MIN_TIME or start > MAX_TIME:
continue # ignora notas fora do intervalo de interesse
# restante do código de desenho...
Se deseja filtrar notas mesmo que sejam mais cedo ou depois, ajuste esses valores e rode.
Isso ajuda a verificar se na janela de tempo que você quer as notas correspondem de fato ao acorde que espera.
Para investigar acordes (notas tocando simultaneamente):
Analise quais notas começam no mesmo tempo (mesmo valor start), frequentemente formando um acorde.
Note que em 8.571s você tem o acorde com as notas 57 (A), 60 (C) e 64 (E), que é acorde de A menor, por exemplo.
Para ajudar você ainda mais:
Se quiser me enviar o trecho midi original (ou o arquivo MIDI), posso ajudar a interpretar as notas e ajustar o visualizador para destacar algum acorde específico, filtrar canais, ou mesmo fazer zoom no tempo.
Quer que eu prepare um filtro e um debug para mostrar exatamente os acordes que acontecem no tempo real, agrupados e exibidos?
Assim fica claro o que está tocando e ajuda a comparar com o esperado. Quer?
def is_black_key(note):
# Notas pretas no piano ocorrem nos semitons 1(C#),3(D#),6(F#),8(G#),10(A#) em relação a C
return ((note - MIN_VISIBLE_NOTE) % 12) in [1,3,6,8,10]
4) Imprima os valores de índice e notas para inspeção na hora do desenho
Antes de desenhar, adicione prints para ver se as notas e posições estão coerentes:
O acorde de Dó maior tem as seguintes notas MIDI na oitava central:
C (Dó) = 60
E (Mi) = 64
G (Sol) = 67
Para essas notas, a chamada white_key_index(60) deve retornar o índice de tecla branca correta (por exemplo, 24 se começar do MIDI 21 = A0).
Se você receber valores incorretos (ex: índice de tecla branca de nota 60 sendo o mesmo da nota 63), as notas desenhadas estarão deslocadas, e aquele acorde D# maior parecerá no lugar do dó maior.
Como resolver facilmente
Garanta que MIN_VISIBLE_NOTE está igual a 21; nunca o altere para outro valor diferente ou ajuste o código para compensar.
Se quiser visualizar uma faixa menor (ex.: só uma oitava), ajuste o código para desenhar só essa faixa e filtre notas fora dela.
Evite alterar os valores das notas antes do cálculo de posição.
Se quiser posso enviar este trecho do código com prints para ajudar você a diagnosticar?
Quer que eu prepare este passo a passo com prints para descobrir o que está deslocando as notas no seu visualizador?
Número MIDI da nota
Número do índice da tecla branca associada (posição horizontal)
Se a tecla é preta ou branca
Permite acompanhar se notas estão sendo mapeadas para posições consistentes.
O que fazer com essa informação
Rode o visualizador e observe a saída no terminal.
Para as notas do acorde de Dó maior (60, 64, 67), verifique se o índice da tecla branca faz sentido (em geral, notas MIDI maiores têm índices maiores).
Se o índice da tecla branca para a nota 60, por exemplo, corresponder à posição que você espera da tecla “Dó”, então está correto.
Se as posições parecerem incorretas ou quase as mesmas para notas MIDI distintas, significa que o cálculo da tecla branca está com algum erro ou offset.
Caso você detecte erro
Pode me mandar a saída do debug para eu te ajudar a encontrar e corrigir o problema no cálculo da tecla.
Quer que eu te ajude a integrar esse trecho completo no seu código atual?
import mido
import pygame
import sys
import cv2
import numpy as np
from collections import defaultdict
# Configurações do piano e MIDI
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
MIN_VISIBLE_NOTE = 21
MAX_VISIBLE_NOTE = 108
FIRST_MIDI_NOTE = MIN_VISIBLE_NOTE
ANIM_DURATION = 0.3
PREROLL = 3.0 # segundos
# Configuração da janela
INITIAL_WIDTH, INITIAL_HEIGHT = 800, 600
PIANO_HEIGHT_RATIO = 0.15
pygame.init()
screen = pygame.display.set_mode((INITIAL_WIDTH, INITIAL_HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("Visualizador MIDI corrigido")
clock = pygame.time.Clock()
def resize_with_letterbox(frame, target_width, target_height):
h, w = frame.shape[:2]
scale = min(target_width / w, target_height / h)
new_w = int(w * scale)
new_h = int(h * scale)
resized_frame = cv2.resize(frame, (new_w, new_h))
canvas = np.zeros((target_height, target_width, 3), dtype=np.uint8)
x_offset = (target_width - new_w) // 2
y_offset = (target_height - new_h) // 2
canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized_frame
return canvas
video_path = "background.mp4"
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir vídeo: {video_path}")
sys.exit(1)
video_paused = False
video_speed = 1.0
video_frame_time_accum = 0.0
video_fps = cap.get(cv2.CAP_PROP_FPS) or 30
current_video_surface = None
def get_video_frame_controlled(delta_time, width, height):
global video_frame_time_accum, video_paused, current_video_surface, cap, video_fps
if video_paused:
return current_video_surface
video_frame_time_accum += delta_time * video_speed
frames_to_advance = int(video_frame_time_accum * video_fps)
if frames_to_advance >= 1:
video_frame_time_accum -= frames_to_advance / video_fps
for _ in range(frames_to_advance -1):
ret = cap.grab()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = resize_with_letterbox(frame, width, height)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
current_video_surface = pygame.surfarray.make_surface(frame)
return current_video_surface
midi_filename = "exemplo.mid"
midi_file = mido.MidiFile(midi_filename)
tempo_bpm = 120
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
notes = []
time_elapsed = 0.0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
if MIN_VISIBLE_NOTE <= msg.note <= MAX_VISIBLE_NOTE:
note_on_times.setdefault(msg.note, []).append(time_elapsed)
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times and note_on_times[msg.note]:
start_time = note_on_times[msg.note].pop(0)
duration = time_elapsed - start_time
if duration <= 0:
duration = 0.01
notes.append((start_time, msg.note, duration))
end_time = midi_file.length
for note, start_list in note_on_times.items():
for start_time in start_list:
duration = end_time - start_time
if duration <= 0:
duration = 0.01
notes.append((start_time, note, duration))
WIDTH, HEIGHT = INITIAL_WIDTH, INITIAL_HEIGHT
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT
def is_black_key(note):
# Correção: cheque pelo valor da nota mod 12 baseado no padrão C=0
return (note % 12) in [1, 3, 6, 8, 10]
def white_key_index(note):
if note < MIN_VISIBLE_NOTE or note > MAX_VISIBLE_NOTE:
return None
count = 0
for n in range(MIN_VISIBLE_NOTE, note):
if not is_black_key(n):
count += 1
return count
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
def lerp(a, b, t):
return a + (b - a) * t
def draw_piano(active_notes, anim_states):
global white_key_width, white_key_height, black_key_width, black_key_height
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
base_color = (255, 255, 255)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.5, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(230*intensity), int(180*intensity))
else:
color = (255, 230, 180)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
base_color = (0, 0, 0)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.3, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(100*intensity), int(100*intensity))
else:
color = (255, 100, 100)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
def calc_velocity(h):
global visible_height
return (visible_height + h) / PREROLL
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0
speed_multiplier = 1.0
speed_step = 0.1
anim_states = {}
running = True
while running:
delta_time = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.VIDEORESIZE:
WIDTH, HEIGHT = event.w, event.h
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
video_paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
video_paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
video_paused = False
anim_states.clear()
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
video_frame_time_accum = 0.0
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
speed_multiplier += speed_step
print(f"Velocidade notas aumentada para {speed_multiplier:.2f}")
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
speed_multiplier = max(0.1, speed_multiplier - speed_step)
print(f"Velocidade notas reduzida para {speed_multiplier:.2f}")
elif event.key == pygame.K_LEFTBRACKET:
video_speed = max(0.1, video_speed - 0.1)
print(f"Velocidade vídeo reduzida para {video_speed:.2f}")
elif event.key == pygame.K_RIGHTBRACKET:
video_speed += 0.1
print(f"Velocidade vídeo aumentada para {video_speed:.2f}")
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
current_video_surface = get_video_frame_controlled(delta_time, WIDTH, HEIGHT)
if current_video_surface:
screen.blit(current_video_surface, (0, 0))
else:
screen.fill((0, 0, 0))
active_notes = set()
keys_to_delete = []
for k in anim_states:
anim_states[k] -= delta_time
if anim_states[k] <= 0:
keys_to_delete.append(k)
for k in keys_to_delete:
del anim_states[k]
for start, note, duration in notes:
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
continue
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = calc_velocity(h) * speed_multiplier
time_since_appear = current_time - (start - PREROLL / speed_multiplier)
if 0 <= time_since_appear <= PREROLL / speed_multiplier:
y = velocity * time_since_appear - h
idx = white_key_index(note)
if idx is None:
continue
if is_black_key(note):
x = idx * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = idx * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
if start <= current_time <= start + duration:
active_notes.add(note)
if note not in anim_states:
anim_states[note] = ANIM_DURATION
draw_piano(active_notes, anim_states)
progress = min(max(current_time / midi_file.length, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
cap.release()
pygame.quit()
sys.exit()
Teste isso para ver seu visualizador interpretando a tonalidade correta!
Se precisar de mais ajuda, só avisar.
Para t em [start, start + duration] a nota deve continuar descendo na velocidade constante para “manter a tecla pressionada”:
Como a nota já está na posição y = visible_height - h em t = start
Vai continuar descendo com velocidade ( v = \frac{visible_height + h}{PREROLL} )
Logo:
[
y(t) = visible_height - h + v \times (t - start)
]
Ao final da nota:
Para t > start + duration, a nota desaparece (não é mais desenhada).
Código exemplificando a atualização do cálculo da posição Y da nota:
python
velocity = (visible_height + h) / PREROLL # velocidade constante
if start - PREROLL <= current_time < start:
# Fase entrada da nota: nota desliza do topo até o teclado
time_since_appear = current_time - (start - PREROLL)
y = velocity * time_since_appear - h
elif start <= current_time <= start + duration:
# Nota sendo "mantida" pressionada e deslizando mais para baixo
elapsed = current_time - start
y = visible_height - h + velocity * elapsed
else:
# Fora do tempo de exibição da nota
y = None
Depois, só desenhar a nota se y não for None e se estiver visível (por exemplo 0 <= y <= screen_height):
python
if y is not None and 0 <= y <= HEIGHT - PIANO_HEIGHT:
pygame.draw.rect(screen, (0, 255, 0), (x, y, width, h))
Integrando essa lógica no seu loop principal
Substitua o trecho onde você calculava a posição da nota para:
python
for start, note, duration in notes:
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
continue
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = (visible_height + h) / PREROLL
if start - PREROLL <= current_time < start:
time_since_appear = current_time - (start - PREROLL)
y = velocity * time_since_appear - h
elif start <= current_time <= start + duration:
elapsed = current_time - start
y = visible_height - h + velocity * elapsed
else:
continue # nota não deverá ser desenhada
idx = white_key_index(note)
if idx is None:
continue
if is_black_key(note):
x = idx * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = idx * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
Resultado esperado:
Notas entram deslizando do topo para o teclado.
Quando chegam ao teclado (início da nota), a ponta do retângulo bate na tecla.
O retângulo continua descendo enquanto a nota dura, representando a tecla sendo mantida pressionada.
Após a duração, a nota some.
Se quiser, posso montar para você o código completo atualizado com essa funcionalidade, integrando com a parte de vídeo, redimensionamento, pausas, etc. Quer que eu faça isso?
import mido
import pygame
import sys
import cv2
import numpy as np
# Configurações gerais
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
MIN_VISIBLE_NOTE = 21
MAX_VISIBLE_NOTE = 108
FIRST_MIDI_NOTE = MIN_VISIBLE_NOTE
ANIM_DURATION = 0.3
PREROLL = 3.0 # segundos
INITIAL_WIDTH, INITIAL_HEIGHT = 800, 600
PIANO_HEIGHT_RATIO = 0.15
pygame.init()
screen = pygame.display.set_mode((INITIAL_WIDTH, INITIAL_HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("Visualizador MIDI com Notas Durando")
clock = pygame.time.Clock()
def resize_with_letterbox(frame, target_width, target_height):
h, w = frame.shape[:2]
scale = min(target_width / w, target_height / h)
new_w = int(w * scale)
new_h = int(h * scale)
resized_frame = cv2.resize(frame, (new_w, new_h))
canvas = np.zeros((target_height, target_width, 3), dtype=np.uint8)
x_offset = (target_width - new_w) // 2
y_offset = (target_height - new_h) // 2
canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized_frame
return canvas
video_path = "background.mp4"
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir vídeo: {video_path}")
sys.exit(1)
video_paused = False
video_speed = 1.0
video_frame_time_accum = 0.0
video_fps = cap.get(cv2.CAP_PROP_FPS) or 30
current_video_surface = None
def get_video_frame_controlled(delta_time, width, height):
global video_frame_time_accum, video_paused, current_video_surface, cap, video_fps
if video_paused:
return current_video_surface
video_frame_time_accum += delta_time * video_speed
frames_to_advance = int(video_frame_time_accum * video_fps)
if frames_to_advance >= 1:
video_frame_time_accum -= frames_to_advance / video_fps
for _ in range(frames_to_advance -1):
ret = cap.grab()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = resize_with_letterbox(frame, width, height)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
current_video_surface = pygame.surfarray.make_surface(frame)
return current_video_surface
midi_filename = "exemplo.mid"
midi_file = mido.MidiFile(midi_filename)
tempo_bpm = 120
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
notes = []
time_elapsed = 0.0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
if MIN_VISIBLE_NOTE <= msg.note <= MAX_VISIBLE_NOTE:
note_on_times.setdefault(msg.note, []).append(time_elapsed)
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times and note_on_times[msg.note]:
start_time = note_on_times[msg.note].pop(0)
duration = time_elapsed - start_time
if duration <= 0:
duration = 0.01
notes.append((start_time, msg.note, duration))
end_time = midi_file.length
for note, start_list in note_on_times.items():
for start_time in start_list:
duration = end_time - start_time
if duration <= 0:
duration = 0.01
notes.append((start_time, note, duration))
WIDTH, HEIGHT = INITIAL_WIDTH, INITIAL_HEIGHT
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT
def is_black_key(note):
return (note % 12) in [1, 3, 6, 8, 10]
def white_key_index(note):
if note < MIN_VISIBLE_NOTE or note > MAX_VISIBLE_NOTE:
return None
count = 0
for n in range(MIN_VISIBLE_NOTE, note):
if not is_black_key(n):
count += 1
return count
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
def lerp(a, b, t):
return a + (b - a) * t
def draw_piano(active_notes, anim_states):
global white_key_width, white_key_height, black_key_width, black_key_height
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
base_color = (255, 255, 255)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.5, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(230*intensity), int(180*intensity))
else:
color = (255, 230, 180)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
base_color = (0, 0, 0)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
intensity = lerp(0.3, 1.0, abs((t*10) % 1 - 0.5)*2)
color = (int(255*intensity), int(100*intensity), int(100*intensity))
else:
color = (255, 100, 100)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
def calc_velocity(h):
global visible_height
return (visible_height + h) / PREROLL
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0
speed_multiplier = 1.0
speed_step = 0.1
anim_states = {}
running = True
while running:
delta_time = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.VIDEORESIZE:
WIDTH, HEIGHT = event.w, event.h
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
video_paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
video_paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
video_paused = False
anim_states.clear()
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
video_frame_time_accum = 0.0
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
speed_multiplier += speed_step
print(f"Velocidade notas aumentada para {speed_multiplier:.2f}")
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
speed_multiplier = max(0.1, speed_multiplier - speed_step)
print(f"Velocidade notas reduzida para {speed_multiplier:.2f}")
elif event.key == pygame.K_LEFTBRACKET:
video_speed = max(0.1, video_speed - 0.1)
print(f"Velocidade vídeo reduzida para {video_speed:.2f}")
elif event.key == pygame.K_RIGHTBRACKET:
video_speed += 0.1
print(f"Velocidade vídeo aumentada para {video_speed:.2f}")
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
current_video_surface = get_video_frame_controlled(delta_time, WIDTH, HEIGHT)
if current_video_surface:
screen.blit(current_video_surface, (0, 0))
else:
screen.fill((0, 0, 0))
active_notes = set()
keys_to_delete = []
for k in anim_states:
anim_states[k] -= delta_time
if anim_states[k] <= 0:
keys_to_delete.append(k)
for k in keys_to_delete:
del anim_states[k]
for start, note, duration in notes:
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
continue
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = (visible_height + h) / PREROLL
# Cálculo da posição y da parte superior do retângulo da nota:
if start - PREROLL <= current_time < start:
time_since_appear = current_time - (start - PREROLL)
y = velocity * time_since_appear - h
elif start <= current_time <= start + duration:
elapsed = current_time - start
y = visible_height - h + velocity * elapsed
else:
continue # fora do intervalo para essa nota
idx = white_key_index(note)
if idx is None:
continue
if is_black_key(note):
x = idx * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = idx * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
# Marcar tecla como ativa enquanto nota está “pressionada”
if start <= current_time <= start + duration:
active_notes.add(note)
if note not in anim_states:
anim_states[note] = ANIM_DURATION
draw_piano(active_notes, anim_states)
progress = min(max(current_time / midi_file.length, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
cap.release()
pygame.quit()
sys.exit()
Esse código deixa as notas descendo do topo, com altura proporcional à duração, e mantendo a tecla “pressionada” na tela enquanto durar a nota!
Se precisar de mais ajustes ou outro recurso, é só falar!
# Dentro do loop de desenho das teclas ativas
t = anim_states.get(note, 0)
duracao_anim = duration_da_nota # passe isso durante o loop
progresso = max(0, min(1, (duration_da_nota - t) / duration_da_nota))
intensity = lerp(0.5, 1.0, progresso)
color = (int(255*intensity), int(230*intensity), int(180*intensity))
3) Atualize o tempo restante da animação proporcionalmente
No lugar de diminuir anim_states[n] sempre por passo fixo, calcule baseado no tempo real do frame para suavizar.
4) Ajuste do desenho do teclado para sobrepor suavemente as notas quando estão chegando
No desenho do piano, desenhe as teclas depois das notas — isso evita que retângulos das notas pareçam “invadir” as áreas do teclado, eliminando “quebra” visual.
Seu código já faz isso, então talvez só precise de ajuste das margens.
5) Código ajustado com margem e animação suavizada para o destaque
Exemplo minimalista:
python
MARGIN_PIANO = 5
visible_height_effective = visible_height - MARGIN_PIANO
# No cálculo da velocidade
velocity = (visible_height_effective + h) / PREROLL
# No loop para anim_states:
for note in list(anim_states.keys()):
elapsed = anim_states[note]
if elapsed <= 0:
del anim_states[note]
else:
# atualizar intensidade baseado no progresso da duração
duracao = duration_dict[note] # salvo em algum lugar
progresso = max(0, min(1, elapsed / duracao))
anim_states[note] = elapsed - delta_time # decrementa
intensity = lerp(0.5, 1.0, progresso)
# usar essa intensidade para o brilho
# Para desenhar as teclas, use a intensidade calculada
6) Resumo
Use margem para evitar que as notas ultrapassem o desenho do piano.
Faça a animação da tecla pressionada durar proporcionalmente à duração da nota.
Garanta que o piano seja desenhado depois das notas.
Ajuste o decremento do tempo da animação para ser proporcional a cada frame para suavidade.
Opcionalmente, você pode suavizar a entrada/saída da animação com interpolação.
Se quiser, posso gerar a versão inteira do seu código com essas correções implementadas para você testar diretamente. Quer que eu faça isso?
import mido
import pygame
import sys
import cv2
import numpy as np
# Configurações gerais
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
MIN_VISIBLE_NOTE = 21
MAX_VISIBLE_NOTE = 108
FIRST_MIDI_NOTE = MIN_VISIBLE_NOTE
ANIM_DURATION = 0.3
PREROLL = 3.0 # segundos
INITIAL_WIDTH, INITIAL_HEIGHT = 800, 600
PIANO_HEIGHT_RATIO = 0.15
pygame.init()
screen = pygame.display.set_mode((INITIAL_WIDTH, INITIAL_HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("Visualizador MIDI com animação melhorada")
clock = pygame.time.Clock()
def resize_with_letterbox(frame, target_width, target_height):
h, w = frame.shape[:2]
scale = min(target_width / w, target_height / h)
new_w = int(w * scale)
new_h = int(h * scale)
resized_frame = cv2.resize(frame, (new_w, new_h))
canvas = np.zeros((target_height, target_width, 3), dtype=np.uint8)
x_offset = (target_width - new_w) // 2
y_offset = (target_height - new_h) // 2
canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized_frame
return canvas
video_path = "background.mp4"
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir vídeo: {video_path}")
sys.exit(1)
video_paused = False
video_speed = 1.0
video_frame_time_accum = 0.0
video_fps = cap.get(cv2.CAP_PROP_FPS) or 30
current_video_surface = None
def get_video_frame_controlled(delta_time, width, height):
global video_frame_time_accum, video_paused, current_video_surface, cap, video_fps
if video_paused:
return current_video_surface
video_frame_time_accum += delta_time * video_speed
frames_to_advance = int(video_frame_time_accum * video_fps)
if frames_to_advance >= 1:
video_frame_time_accum -= frames_to_advance / video_fps
for _ in range(frames_to_advance -1):
ret = cap.grab()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = resize_with_letterbox(frame, width, height)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
current_video_surface = pygame.surfarray.make_surface(frame)
return current_video_surface
midi_filename = "exemplo.mid"
midi_file = mido.MidiFile(midi_filename)
tempo_bpm = 120
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
notes = []
time_elapsed = 0.0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
if MIN_VISIBLE_NOTE <= msg.note <= MAX_VISIBLE_NOTE:
note_on_times.setdefault(msg.note, []).append(time_elapsed)
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times and note_on_times[msg.note]:
start_time = note_on_times[msg.note].pop(0)
duration = time_elapsed - start_time
if duration <= 0:
duration = 0.01
notes.append((start_time, msg.note, duration))
end_time = midi_file.length
for note, start_list in note_on_times.items():
for start_time in start_list:
duration = end_time - start_time
if duration <= 0:
duration = 0.01
notes.append((start_time, note, duration))
WIDTH, HEIGHT = INITIAL_WIDTH, INITIAL_HEIGHT
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
MARGIN_PIANO = 5 # margem para evitar overlap visual
visible_height = HEIGHT - PIANO_HEIGHT - MARGIN_PIANO
def is_black_key(note):
return (note % 12) in [1, 3, 6, 8, 10]
def white_key_index(note):
if note < MIN_VISIBLE_NOTE or note > MAX_VISIBLE_NOTE:
return None
count = 0
for n in range(MIN_VISIBLE_NOTE, note):
if not is_black_key(n):
count += 1
return count
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
def lerp(a, b, t):
return a + (b - a) * t
def draw_piano(active_notes, anim_states, anim_durations):
global white_key_width, white_key_height, black_key_width, black_key_height
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
base_color = (255, 255, 255)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
# intensidade baseada no progresso da duração da nota para suavizar fade
t = anim_states[n]
dur = anim_durations.get(n, ANIM_DURATION)
progresso = max(0.0, min(1.0, t / dur))
intensity = lerp(0.5, 1.0, progresso)
color = (int(255*intensity), int(230*intensity), int(180*intensity))
else:
color = (255, 230, 180)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
base_color = (0, 0, 0)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
dur = anim_durations.get(n, ANIM_DURATION)
progresso = max(0.0, min(1.0, t / dur))
intensity = lerp(0.3, 1.0, progresso)
color = (int(255*intensity), int(100*intensity), int(100*intensity))
else:
color = (255, 100, 100)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
def calc_velocity(h):
global visible_height
return (visible_height + h) / PREROLL
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0
speed_multiplier = 1.0
speed_step = 0.1
anim_states = {} # tecla: tempo restante de animação (fade)
anim_durations = {} # tecla: duração total da nota para animação suave
running = True
while running:
delta_time = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.VIDEORESIZE:
WIDTH, HEIGHT = event.w, event.h
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT - MARGIN_PIANO
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
video_paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
video_paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
video_paused = False
anim_states.clear()
anim_durations.clear()
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
video_frame_time_accum = 0.0
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
speed_multiplier += speed_step
print(f"Velocidade notas aumentada para {speed_multiplier:.2f}")
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
speed_multiplier = max(0.1, speed_multiplier - speed_step)
print(f"Velocidade notas reduzida para {speed_multiplier:.2f}")
elif event.key == pygame.K_LEFTBRACKET:
video_speed = max(0.1, video_speed - 0.1)
print(f"Velocidade vídeo reduzida para {video_speed:.2f}")
elif event.key == pygame.K_RIGHTBRACKET:
video_speed += 0.1
print(f"Velocidade vídeo aumentada para {video_speed:.2f}")
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
current_video_surface = get_video_frame_controlled(delta_time, WIDTH, HEIGHT)
if current_video_surface:
screen.blit(current_video_surface, (0, 0))
else:
screen.fill((0, 0, 0))
active_notes = set()
keys_to_delete = []
# Atualiza animação com fade proporcional à duração da nota
for key in list(anim_states.keys()):
anim_states[key] -= delta_time
if anim_states[key] <= 0:
keys_to_delete.append(key)
for key in keys_to_delete:
del anim_states[key]
del anim_durations[key]
for start, note, duration in notes:
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
continue
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = (visible_height + h) / PREROLL
if start - PREROLL <= current_time < start:
time_since_appear = current_time - (start - PREROLL)
y = velocity * time_since_appear - h
elif start <= current_time <= start + duration:
elapsed = current_time - start
y = visible_height - h + velocity * elapsed
else:
continue
idx = white_key_index(note)
if idx is None:
continue
if is_black_key(note):
x = idx * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = idx * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
if start <= current_time <= start + duration:
active_notes.add(note)
# Armazena duração e reinicia animação pra chave
anim_durations[note] = duration
if note not in anim_states:
anim_states[note] = duration # duração da animação = duração da nota
draw_piano(active_notes, anim_states, anim_durations)
progress = min(max(current_time / midi_file.length, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
cap.release()
pygame.quit()
sys.exit()
O que mudou/resolvido?
Margem (MARGIN_PIANO) para evitar os retângulos ultrapassarem visualmente o topo do piano, eliminando efeito “invasão” da nota.
Animação da tecla pressionada que dura a mesma duração da nota, com fade gradual, evitando piscadas abruptas.
O piano é desenhado por último, mantendo o foreground e cobrindo visualmente a base das notas.
Teste esse código e veja se a experiência ficou mais fluida e visualmente agradável.
Se quiser, posso ajudar a ajustar cores / efeitos ou adicionar outros recursos!
for start, note, duration in notes:
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
continue
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = (visible_height + h) / PREROLL
# Definir os tempos limites para exibição da nota (desde antes do início até depois do fim)
note_appear_start = start - PREROLL
note_appear_end = start + duration + PREROLL # algum "extra" para garantir que desapareça fora da tela
if note_appear_start <= current_time <= note_appear_end:
if current_time < start:
# Nota deslizando para baixo, ainda não chegou no teclado
time_since_appear = current_time - note_appear_start
y = velocity * time_since_appear - h
else:
# Nota pressionando tecla e descendo depois
elapsed_since_start = current_time - start
y = visible_height - h + velocity * elapsed_since_start
if y <= HEIGHT:
# Só desenha se dentro da janela, evita desenhar fora da tela
idx = white_key_index(note)
if idx is None:
continue
if is_black_key(note):
x = idx * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = idx * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
# Marcar tecla ativa enquanto nota está tocando
if start <= current_time <= start + duration:
active_notes.add(note)
anim_durations[note] = duration
if note not in anim_states:
anim_states[note] = duration
else:
# Fora do intervalo amplo, não desenha
pass
Pontos importantes:
Use um intevalo um pouco maior para sumir a nota depois do fim da duração (note_appear_end), para evitar “sumir no meio” da tela.
Cheque sempre (antes de desenhar) se a posição Y está dentro da janela para evitar desenho desnecessário (isso evita “saltos” visuais).
Sempre faça a lógica de desenho das notas em ordem contínua, sem “reset” para cima.
Resumo das recomendações:
Ajuste o intervalo de exibição da nota para que ela não reapareça de forma errada (mais cedo do que deveria ou repetidamente).
Limite o desenho somente entre tempos mínimos e máximos calculados para cada nota.
Use o y crescente de forma contínua relacionada ao tempo atual da música para evitar “saltos”.
Ajuste a margem (offset) para evitar ultrapassar o piano visualmente — você já tinha esse ajuste.
Se quiser, posso montar pra você uma versão corrigida completa com essas melhorias aplicadas no loop de desenho de notas, integrada ao seu código atual. Quer?
import mido
import pygame
import sys
import cv2
import numpy as np
NUM_WHITE_KEYS = 52
NUM_KEYS = 88
MIN_VISIBLE_NOTE = 21
MAX_VISIBLE_NOTE = 108
ANIM_DURATION = 0.3
PREROLL = 3.0 # segundos
INITIAL_WIDTH, INITIAL_HEIGHT = 800, 600
PIANO_HEIGHT_RATIO = 0.15
MARGIN_PIANO = 5 # margem para notas não passarem visivelmente do piano
pygame.init()
screen = pygame.display.set_mode((INITIAL_WIDTH, INITIAL_HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("Visualizador MIDI - Sem saltos na animação")
clock = pygame.time.Clock()
def resize_with_letterbox(frame, target_width, target_height):
h, w = frame.shape[:2]
scale = min(target_width / w, target_height / h)
new_w = int(w * scale)
new_h = int(h * scale)
resized_frame = cv2.resize(frame, (new_w, new_h))
canvas = np.zeros((target_height, target_width, 3), dtype=np.uint8)
x_offset = (target_width - new_w) // 2
y_offset = (target_height - new_h) // 2
canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized_frame
return canvas
video_path = "background.mp4"
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Erro ao abrir vídeo: {video_path}")
sys.exit(1)
video_paused = False
video_speed = 1.0
video_frame_time_accum = 0.0
video_fps = cap.get(cv2.CAP_PROP_FPS) or 30
current_video_surface = None
def get_video_frame_controlled(delta_time, width, height):
global video_frame_time_accum, video_paused, current_video_surface, cap, video_fps
if video_paused:
return current_video_surface
video_frame_time_accum += delta_time * video_speed
frames_to_advance = int(video_frame_time_accum * video_fps)
if frames_to_advance >= 1:
video_frame_time_accum -= frames_to_advance / video_fps
for _ in range(frames_to_advance -1):
ret = cap.grab()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
frame = resize_with_letterbox(frame, width, height)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
current_video_surface = pygame.surfarray.make_surface(frame)
return current_video_surface
midi_filename = "exemplo.mid"
midi_file = mido.MidiFile(midi_filename)
tempo_bpm = 120
for track in midi_file.tracks:
for msg in track:
if msg.type == 'set_tempo':
tempo_bpm = mido.tempo2bpm(msg.tempo)
break
else:
continue
break
print(f"BPM detectado: {tempo_bpm}")
notes = []
time_elapsed = 0.0
note_on_times = {}
for msg in midi_file:
time_elapsed += msg.time
if msg.type == 'note_on' and msg.velocity > 0:
if MIN_VISIBLE_NOTE <= msg.note <= MAX_VISIBLE_NOTE:
note_on_times.setdefault(msg.note, []).append(time_elapsed)
elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
if msg.note in note_on_times and note_on_times[msg.note]:
start_time = note_on_times[msg.note].pop(0)
duration = time_elapsed - start_time
if duration <= 0:
duration = 0.01
notes.append((start_time, msg.note, duration))
end_time = midi_file.length
for note, start_list in note_on_times.items():
for start_time in start_list:
duration = end_time - start_time
if duration <= 0:
duration = 0.01
notes.append((start_time, note, duration))
WIDTH, HEIGHT = INITIAL_WIDTH, INITIAL_HEIGHT
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT - MARGIN_PIANO
def is_black_key(note):
return (note % 12) in [1, 3, 6, 8, 10]
def white_key_index(note):
if note < MIN_VISIBLE_NOTE or note > MAX_VISIBLE_NOTE:
return None
count = 0
for n in range(MIN_VISIBLE_NOTE, note):
if not is_black_key(n):
count += 1
return count
NOTE_WIDTH_MULT = 0.9
NOTE_HEIGHT_MIN = 4
NOTE_HEIGHT_MAX = 40
def lerp(a, b, t):
return a + (b - a) * t
def draw_piano(active_notes, anim_states, anim_durations):
global white_key_width, white_key_height, black_key_width, black_key_height
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if not is_black_key(n):
x = white_key_index(n) * white_key_width
base_color = (255, 255, 255)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
dur = anim_durations.get(n, ANIM_DURATION)
progresso = max(0.0, min(1.0, t / dur))
intensity = lerp(0.5, 1.0, progresso)
color = (int(255*intensity), int(230*intensity), int(180*intensity))
else:
color = (255, 230, 180)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, white_key_width, white_key_height))
pygame.draw.rect(screen, (0, 0, 0), (x, HEIGHT - white_key_height, white_key_width, white_key_height), 1)
for n in range(MIN_VISIBLE_NOTE, MAX_VISIBLE_NOTE + 1):
if is_black_key(n):
x = white_key_index(n) * white_key_width - black_key_width / 2
base_color = (0, 0, 0)
if n in active_notes:
if n in anim_states and anim_states[n] > 0:
t = anim_states[n]
dur = anim_durations.get(n, ANIM_DURATION)
progresso = max(0.0, min(1.0, t / dur))
intensity = lerp(0.3, 1.0, progresso)
color = (int(255*intensity), int(100*intensity), int(100*intensity))
else:
color = (255, 100, 100)
else:
color = base_color
pygame.draw.rect(screen, color, (x, HEIGHT - white_key_height, black_key_width, black_key_height))
start_ticks = pygame.time.get_ticks()
paused = False
pause_start_time = 0
time_paused_accum = 0
speed_multiplier = 1.0
speed_step = 0.1
anim_states = {}
anim_durations = {}
running = True
while running:
delta_time = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.VIDEORESIZE:
WIDTH, HEIGHT = event.w, event.h
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
PIANO_HEIGHT = int(HEIGHT * PIANO_HEIGHT_RATIO)
white_key_width = WIDTH / NUM_WHITE_KEYS
white_key_height = PIANO_HEIGHT
black_key_width = white_key_width * 0.6
black_key_height = white_key_height * 0.6
visible_height = HEIGHT - PIANO_HEIGHT - MARGIN_PIANO
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not paused:
pause_start_time = pygame.time.get_ticks()
paused = True
video_paused = True
else:
time_paused_accum += pygame.time.get_ticks() - pause_start_time
paused = False
video_paused = False
elif event.key == pygame.K_r:
start_ticks = pygame.time.get_ticks()
time_paused_accum = 0
paused = False
video_paused = False
anim_states.clear()
anim_durations.clear()
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
video_frame_time_accum = 0.0
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
speed_multiplier += speed_step
print(f"Velocidade notas aumentada para {speed_multiplier:.2f}")
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
speed_multiplier = max(0.1, speed_multiplier - speed_step)
print(f"Velocidade notas reduzida para {speed_multiplier:.2f}")
elif event.key == pygame.K_LEFTBRACKET:
video_speed = max(0.1, video_speed - 0.1)
print(f"Velocidade vídeo reduzida para {video_speed:.2f}")
elif event.key == pygame.K_RIGHTBRACKET:
video_speed += 0.1
print(f"Velocidade vídeo aumentada para {video_speed:.2f}")
if paused:
current_time = (pause_start_time - start_ticks - time_paused_accum) / 1000.0
else:
current_time = (pygame.time.get_ticks() - start_ticks - time_paused_accum) / 1000.0
current_video_surface = get_video_frame_controlled(delta_time, WIDTH, HEIGHT)
if current_video_surface:
screen.blit(current_video_surface, (0, 0))
else:
screen.fill((0, 0, 0))
active_notes = set()
keys_to_delete = []
# Atualiza animação com duração proporcional
for key in list(anim_states.keys()):
anim_states[key] -= delta_time
if anim_states[key] <= 0:
keys_to_delete.append(key)
for key in keys_to_delete:
del anim_states[key]
del anim_durations[key]
for start, note, duration in notes:
if not (MIN_VISIBLE_NOTE <= note <= MAX_VISIBLE_NOTE):
continue
h = max(NOTE_HEIGHT_MIN, min(NOTE_HEIGHT_MAX, duration / PREROLL * visible_height))
velocity = (visible_height + h) / PREROLL
note_appear_start = start - PREROLL
note_appear_end = start + duration + PREROLL # desenho até um pouco depois
if note_appear_start <= current_time <= note_appear_end:
if current_time < start:
time_since_appear = current_time - note_appear_start
y = velocity * time_since_appear - h
else:
elapsed = current_time - start
y = visible_height - h + velocity * elapsed
if y <= HEIGHT:
idx = white_key_index(note)
if idx is None:
continue
if is_black_key(note):
x = idx * white_key_width - black_key_width / 2
w = black_key_width * NOTE_WIDTH_MULT
else:
x = idx * white_key_width
w = white_key_width * NOTE_WIDTH_MULT
pygame.draw.rect(screen, (0, 255, 0), (x, y, w, h))
if start <= current_time <= start + duration:
active_notes.add(note)
anim_durations[note] = duration
if note not in anim_states:
anim_states[note] = duration
else:
# fora do intervalo de exibição da nota
continue
draw_piano(active_notes, anim_states, anim_durations)
progress = min(max(current_time / midi_file.length, 0), 1)
pygame.draw.rect(screen, (100, 100, 255), (0, 0, WIDTH * progress, 5))
pygame.display.flip()
cap.release()
pygame.quit()
sys.exit()
O que mudou e por quê
note_appear_end = final do tempo de exibição da nota, deixando espaço para a nota sair SUAVEMENTE da tela.
Só desenha a nota se current_time estiver entre note_appear_start e note_appear_end, evitando reaparecimentos ou pulos.
Usa margem para evitar que o retângulo da nota "invada" visualmente o piano.
O destaque na tecla (anim_states) é proporcional à duração e faz fade suave.
Pode ajustar esses valores para mais suavidade ou timing.
Com essas mudanças as notas não devem mais "voltar" para cima repentinamente nem piscar.