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程序设计有所帮助。

相关文章

pywinauto自动化操作记事本

一、什么是pywinauto Pywinauto是基于Python开发的,用于操作Windows标准图形界面的自动化测试的脚本模块。 二、pywinauto可以用来做什么 1.可以应用在...

Python利用正则表达式匹配并截取指定子串及去重的方法

本文实例讲述了Python利用正则表达式匹配并截取指定子串及去重的方法。分享给大家供大家参考。具体如下: import re pattern=re.compile(r'\| (\d+...

Python psutil模块简单使用实例

安装很简单 复制代码 代码如下: pip install psutil 官网地址为: https://pythonhosted.org/psutil/ (文档上有详细的api) git...

解决pyqt中ui编译成窗体.py中文乱码的问题

我在Eric工具下编译的 解决办法: 1、打开 C:\Python27\Lib\site-packages\eric4\i18n,将中文资源包的名称"GB2312."去掉,变成eric4...

使用opencv将视频帧转成图片输出

使用opencv将视频帧转成图片输出

本文做的是基于opencv将视频帧转成图片输出,由于一个视频包含的帧数过多,经常我们并不是需要它的全部帧转成图片,因此我们希望可以设置每隔多少帧再转一次图片(本文设置为30帧),若有人需...