python 用Python播放MIDI文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 用Python播放MIDI文件相关的知识,希望对你有一定的参考价值。

# see: https://www.daniweb.com/programming/software-development/code/216976/play-a-midi-music-file-using-pygame

# sudo pip install pygame

# on ubuntu
# sudo apt-get install python-pygame

import pygame

def play_music(music_file):
    """
    stream music with mixer.music module in blocking manner
    this will stream the sound from disk while playing
    """
    clock = pygame.time.Clock()
    try:
        pygame.mixer.music.load(music_file)
        print "Music file %s loaded!" % music_file
    except pygame.error:
        print "File %s not found! (%s)" % (music_file, pygame.get_error())
        return
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        # check if playback has finished
        clock.tick(30)
# pick a midi music file you have ...
# (if not in working folder use full path)

midi_file = './data/clean_midi/808 State/Pacific 202.mid'
freq = 44100    # audio CD quality
bitsize = -16   # unsigned 16 bit
channels = 2    # 1 is mono, 2 is stereo
buffer = 1024    # number of samples
pygame.mixer.init(freq, bitsize, channels, buffer)

# optional volume 0 to 1.0
pygame.mixer.music.set_volume(0.8)
try:
    play_music(midi_file)
except KeyboardInterrupt:
    # if user hits Ctrl/C then exit
    # (works only in console mode)
    pygame.mixer.music.fadeout(1000)
    pygame.mixer.music.stop()
    raise SystemExit

以上是关于python 用Python播放MIDI文件的主要内容,如果未能解决你的问题,请参考以下文章

在 python 中播放 MIDI 文件?

如何使用 python 从头开始​​编写 Midi 文件

在 Python 中为 Kivy 播放跨平台、移动、MIDI - 这可能吗?

在 python 中构建 MIDI 合并程序,带有恢复选项

如何使用 Python 中的长笛乐器从音符制作 MIDI 文件(music21 库)

如何“减慢” MIDI 文件(最好在 Python 中)?