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安装模块如何通过setup.py安装(超简单)

python安装模块如何通过setup.py安装(超简单)

有些时候我们发现一些模块没有提供pip install 命令和安装教程 , 只提供了一个setup.py文件 , 这个时候如何安装呢? 步骤 打开cmd 到达安装目录...

关于python之字典的嵌套,递归调用方法

一 字典的嵌套 在机器学习实战决策树部分,生成决策树时用到了字典的嵌套。 >>>s1={'no surface':{}} >>>s1['no su...

python通过getopt模块如何获取执行的命令参数详解

前言 python脚本和shell脚本一样可以获取命令行的参数,根据不同的参数,执行不同的逻辑处理。 通常我们可以通过getopt模块获得不同的执行命令和参数。下面话不多说了,来一起看看...

利用Python读取文件的四种不同方法比对

前言 大家都知道Python 读文件的方式多种多样,但是当需要读取一个大文件的时候,不同的读取方式会有不一样的效果。下面就来看看详细的介绍吧。 场景 逐行读取一个 2.9G 的大文件...

python双向链表原理与实现方法详解

本文实例讲述了python双向链表原理与实现方法。分享给大家供大家参考,具体如下: 双向链表 一种更复杂的链表是“双向链表”或“双面链表”。每个节点有两个链接:一个指向前一个节点,当此节...