Creating iPhone-compatible movies with PyObjC and QTKit

As part of some general messing around with PyObjC and QTKit, I wrote a short script for converting a movie (anything readable by QuickTime) into an iPhone-compatible format. It's basically a Python version of an Objective-C example from Apple.

The code:

#!/usr/bin/python

import struct

import QTKit


class QuickTimeError(Exception):

    @classmethod
    def from_nserror(cls, nserror):
        return cls(nserror.userInfo()['NSLocalizedDescription'])


def long_from_string(s):
    return struct.unpack('>l', s)[0]


def convert_for_iphone(infile, outfile):
    in_attrs = {
        'QTMovieFileNameAttribute': unicode(infile),
        'QTMovieOpenAsyncOKAttribute': False,
        'QTMovieApertureModeAttribute': QTKit.QTMovieApertureModeClean,
        'QTMovieIsActiveAttribute': True,
        }

    movie, error = QTKit.QTMovie.movieWithAttributes_error_(in_attrs, None)
    if movie is None:
        raise QuickTimeError.from_nserror(error)

    out_attrs = {
        'QTMovieExport': True,
        'QTMovieExportType': long_from_string('M4VP'),
        }

    status, error = movie.writeToFile_withAttributes_error_(unicode(outfile),
                                                            out_attrs,
                                                            None)
    if not status:
        raise QuickTimeError.from_nserror(error)


if __name__ == '__main__':
    import sys

    infile = sys.argv[1]
    outfile = sys.argv[2]

    convert_for_iphone(infile, outfile)

To use it:

$ ./convert_for_iphone infile outfile

I've only tested it with the system Python under Leopard. While the script isn't all that useful in itself, it may serve as a helpful example to someone. Sure the hell beats doing the same job with AppleScript.

Tags: apple, iphone, pyobjc, python, qtkit
Wed, 20 Feb 2008 00:11 UTC

« Next