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实现对象转换为xml的方法示例

本文实例讲述了Python实现对象转换为xml的方法。分享给大家供大家参考,具体如下: # -*- coding:UTF-8 -*- ''''' Created on 2010-4-...

Django处理多用户类型的方法介绍

Django处理多用户类型的方法介绍

起步 这是许多开发者在项目初期要面临的一个普遍问题。要怎样来处理多用户类型。 本文讲介绍对于不同场景和业务需求如何设计用户模型。为项目提供指导设计。 设计之前 在梳理用户设计之前,有...

在Python中使用判断语句和循环的教程

条件判断 计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。 比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用if语句实现: age = 20 if a...

使用Python进行二进制文件读写的简单方法(推荐)

总的感觉,python本身并没有对二进制进行支持,不过提供了一个模块来弥补,就是struct模块。 python没有二进制类型,但可以存储二进制类型的数据,就是用string字符串类型来...

Python如何使用k-means方法将列表中相似的句子归类

Python如何使用k-means方法将列表中相似的句子归类

前言 由于今年暑假在学习一些自然语言处理的东西,发现网上对k-means的讲解不是很清楚,网上大多数代码只是将聚类结果以图片的形式呈现,而不是将聚类的结果表示出来,于是我将老师给的代码和...