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基于urllib实现按照百度音乐分类下载mp3的方法

本文实例讲述了python基于urllib实现按照百度音乐分类下载mp3的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python #-*- cod...

python实现简单flappy bird

本文实例为大家分享了python实现flappy bird的简单代码,供大家参考,具体内容如下 import pygame from pygame.locals import * f...

一行Python代码制作动态二维码的实现

一行Python代码制作动态二维码的实现

在GitHub上发现了一个比较有意思的项目,只需要一行Python代码就可以快捷方便生成普通二维码、艺术二维码(黑白/彩色)和动态GIF二维码。 GitHub网站参加:https://g...

mac下pycharm设置python版本的图文教程

mac下pycharm设置python版本的图文教程

安装了pycharm 5.0.1,创建了测试项目,发现python的版本是2.6.9的,系统自带的版本好像是2.7的,为什么这样,怎么切换到2.7 看了一下系统到底装了些什么版本 居...

Python写的一个定时重跑获取数据库数据

Python写的一个定时重跑获取数据库数据

做大数据的童鞋经常会写定时任务跑数据,由于任务之间的依赖(一般都是下游依赖上游的数据产出),所以经常会导致数据获取失败,因为很多人发现数据失败后 都会去查看日志,然后手动去执行自己的任务...