PageRenderTime 45ms CodeModel.GetById 27ms app.highlight 12ms RepoModel.GetById 1ms app.codeStats 1ms

/src/echonest/support/midi/RawOutstreamFile.py

http://echo-nest-remix.googlecode.com/
Python | 69 lines | 56 code | 5 blank | 8 comment | 0 complexity | ce1635fc768be1cdbbbe2e4f9a90313b MD5 | raw file
 1# -*- coding: ISO-8859-1 -*-
 2
 3# standard library imports
 4import sys
 5from types import StringType
 6from struct import unpack
 7from cStringIO import StringIO
 8
 9# custom import
10from DataTypeConverters import writeBew, writeVar, fromBytes
11
12class 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
59if __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()