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

http://echo-nest-remix.googlecode.com/ · Python · 69 lines · 41 code · 19 blank · 9 comment · 5 complexity · ce1635fc768be1cdbbbe2e4f9a90313b MD5 · raw file

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