1
+ import pyaudio
2
+ import wave
3
+ import struct
4
+ import sys
5
+ import math
6
+
7
+ class Audio :
8
+ """
9
+
10
+ """
11
+ def __init__ (self , filename , chunksize , paudio ):
12
+ filestream = wave .open (filename , "rb" )
13
+
14
+ self .audiostream = paudio .open (format = paudio .get_format_from_width (filestream .getsampwidth ()),
15
+ channels = filestream .getnchannels (),
16
+ rate = filestream .getframerate (),
17
+ output = True )
18
+
19
+ self .progress = 0.0
20
+ self .pitch = 1.0
21
+ self .volume = 1.0
22
+ self .chunksize = chunksize
23
+
24
+ # We store the data as integers here
25
+ self .audiodata = []
26
+
27
+ # These formats should work most of the time
28
+ # See: https://docs.python.org/2/library/struct.html#format-characters
29
+ types = {1 : 'B' , 2 : 'h' , 4 : 'i' }
30
+ self .type = types [filestream .getsampwidth ()]
31
+ # Check for system byteorder
32
+ endianness = {"big" : '>' , "little" : '<' }
33
+ self .endianness = endianness [sys .byteorder ]
34
+
35
+ audiodata = filestream .readframes (chunksize )
36
+
37
+ while (audiodata ):
38
+ fmt = self .endianness + self .type * int (len (audiodata ) / filestream .getsampwidth ())
39
+ data = struct .unpack (fmt , audiodata )
40
+ self .audiodata .extend (data )
41
+ audiodata = filestream .readframes (chunksize )
42
+
43
+ filestream .close ()
44
+
45
+ while (True ):
46
+ self .process ()
47
+
48
+ def __del__ (self ):
49
+ self .audiostream .stop_stream ()
50
+ self .audiostream .close ()
51
+
52
+ def process (self ):
53
+ if (self .progress > len (self .audiodata )):
54
+ return
55
+ readout = self .pitch * float (self .chunksize )
56
+ index = math .floor (self .progress )
57
+ count = math .ceil (readout )
58
+ subdata = self .audiodata [index : min (index + count , len (self .audiodata ))]
59
+ fmt = self .endianness + self .type * len (subdata )
60
+ audiodata = struct .pack (fmt , * subdata )
61
+ self .audiostream .write (audiodata )
62
+ self .progress += readout
63
+
64
+ paudio = pyaudio .PyAudio ()
65
+
66
+ audio = Audio ("MenuTheme2_final.wav" , 1024 , paudio )
67
+
68
+ paudio .terminate ()
0 commit comments