python使用PyGame播放Midi和Mp3文件的方法

yipeiwu_com5年前Python基础

本文实例讲述了python使用PyGame播放Midi和Mp3文件的方法。分享给大家供大家参考。具体实现方法如下:

''' pg_midi_sound101.py
play midi music files (also mp3 files) using pygame
tested with Python273/331 and pygame192 by vegaseat
'''
import pygame as pg
def play_music(music_file):
  '''
  stream music with mixer.music module in blocking manner
  this will stream the sound from disk while playing
  '''
  clock = pg.time.Clock()
  try:
    pg.mixer.music.load(music_file)
    print("Music file {} loaded!".format(music_file))
  except pygame.error:
    print("File {} not found! {}".format(music_file, pg.get_error()))
    return
  pg.mixer.music.play()
  # check if playback has finished
  while pg.mixer.music.get_busy():
    clock.tick(30)
# pick a midi or MP3 music file you have in the working folder
# or give full pathname
music_file = "Latin.mid"
#music_file = "Drumtrack.mp3"
freq = 44100  # audio CD quality
bitsize = -16  # unsigned 16 bit
channels = 2  # 1 is mono, 2 is stereo
buffer = 2048  # number of samples (experiment to get right sound)
pg.mixer.init(freq, bitsize, channels, buffer)
# optional volume 0 to 1.0
pg.mixer.music.set_volume(0.8)
try:
  play_music(music_file)
except KeyboardInterrupt:
  # if user hits Ctrl/C then exit
  # (works only in console mode)
  pg.mixer.music.fadeout(1000)
  pg.mixer.music.stop()
  raise SystemExit

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python实现图片拼接的代码

具体代码如下所示: import os from PIL import Image UNIT_SIZE = 220 # the size of image save_path = '...

Python随机读取文件实现实例

Python随机读取文件 代码如下 import os import random rootdir = "d:\\face\\train" file_names = [] for...

在Python下尝试多线程编程

多任务可以由多进程完成,也可以由一个进程内的多线程完成。 我们前面提到了进程是由若干线程组成的,一个进程至少有一个线程。 由于线程是操作系统直接支持的执行单元,因此,高级语言通常都内置多...

Python 脚本的三种执行方式小结

Python 脚本的三种执行方式小结

1.交互模式下执行 Python,这种模式下,无需创建脚本文件,直接在 Python解释器的交互模式下编写对应的 Python 语句即可。 1)打开交互模式的方式: Windows下:...

详解windows python3.7安装numpy问题的解决方法

详解windows python3.7安装numpy问题的解决方法

我的是win7的系统,去python官网下载python3.7安装 CMD  #打开命令窗口 pip install numpy #在cmd中输入 提示 需要c++14....