Python uses PyGame to play Midi and Mp3 files

Source: Internet
Author: User

Python uses PyGame to play Midi and Mp3 files

Python uses PyGame to play Midi and Mp3 files

This article describes how to use PyGame to play Midi and Mp3 files in python. Share it with you for your reference. The specific implementation method is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

'''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 ))

Failed t 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.pdf"

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 t KeyboardInterrupt:

# If user hits Ctrl/C then exit

# (Works only in console mode)

Pg. mixer. music. fadeout (1000)

Pg. mixer. music. stop ()

Raise SystemExit

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.