73eed316e99bc7e3b16c49856dfdb1aad77f1db9
[minwii.git] / src / mxmMidi / RawOutstreamFile.py
1 # -*- coding: ISO-8859-1 -*-
2
3 # standard library imports
4 import sys
5 from types import StringType
6 from struct import unpack
7 from cStringIO import StringIO
8
9 # custom import
10 from DataTypeConverters import writeBew, writeVar, fromBytes
11
12 class RawOutstreamFile:
13
14 """
15
16 Writes a midi file to disk.
17
18 """
19
20 def __init__(self, outfile=''):
21 self.buffer = StringIO()
22 self.outfile = outfile
23
24
25 # native data reading functions
26
27
28 def writeSlice(self, str_slice):
29 "Writes the next text slice to the raw data"
30 self.buffer.write(str_slice)
31
32
33 def writeBew(self, value, length=1):
34 "Writes a value to the file as big endian word"
35 self.writeSlice(writeBew(value, length))
36
37
38 def writeVarLen(self, value):
39 "Writes a variable length word to the file"
40 var = self.writeSlice(writeVar(value))
41
42
43 def write(self):
44 "Writes to disc"
45 if self.outfile:
46 if isinstance(self.outfile, StringType):
47 outfile = open(self.outfile, 'wb')
48 outfile.write(self.getvalue())
49 outfile.close()
50 else:
51 self.outfile.write(self.getvalue())
52 else:
53 sys.stdout.write(self.getvalue())
54
55 def getvalue(self):
56 return self.buffer.getvalue()
57
58
59 if __name__ == '__main__':
60
61 out_file = 'test/midifiles/midiout.mid'
62 out_file = ''
63 rawOut = RawOutstreamFile(out_file)
64 rawOut.writeSlice('MThd')
65 rawOut.writeBew(6, 4)
66 rawOut.writeBew(1, 2)
67 rawOut.writeBew(2, 2)
68 rawOut.writeBew(15360, 2)
69 rawOut.write()