SHARE
TWEET

compressMP3_MP

a guest Jun 28th, 2012 50 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python
  2. # -*- coding: utf8 -*-
  3. # This script converts all media files within the current directory which match the
  4. # search pattern into MP3 files.
  5.  
  6. # Import required modules
  7. import os, re, multiprocessing
  8.  
  9. # Init Queue for found media files
  10. q = multiprocessing.Queue()
  11.  
  12. # Function to encode MP3 files
  13. def encodeAudio ():
  14.   while not q.empty():
  15.     # Get next entry out of file queue
  16.     sourcefile = q.get()
  17.     print sourcefile
  18.     targetfile = sourcefile[:-3] + 'mp3'
  19.     # Feel free to adjust the encoding tool used and its parameters :)
  20.     commandline = "ffmpeg -i \"" + sourcefile  +  "\" -acodec libmp3lame -ac 2 -ab 192k -vn -y \""+ targetfile + "\""
  21.     os.popen (commandline)
  22.  
  23. # Find out how many CPU cores the host has
  24. # Beware: I am not shure how Intel CPUs with Hyperthreading react. They report each thread as logical CPU but spawning an
  25. #         encoding thread for each "CPU" might apply too heavy load to the host. You should consider setting cores to a
  26. #         constant value then.
  27. cores=multiprocessing.cpu_count()
  28.  
  29. # Definition of extensions you want to search for. Only add lowercased extensions here as
  30. # the are automatically added in their uppercased version.
  31. extensions = ['avi','flv', 'mp4', 'wav', 'ogg', 'mpg', 'aac', 'flac' ]
  32.  
  33. # Generate search pattern from extension list
  34. pattern = ''
  35.  
  36. for n in extensions:
  37.   if len(pattern) > 0: pattern += '|'
  38.   pattern = pattern + n  + '|' + n.upper()
  39.  
  40. # Build regular expression for search pattern
  41. expr = re.compile (".*\.(" + pattern  + ")$")
  42.  
  43. # Read all files from current directory
  44. files = os.listdir('.')  
  45.  
  46. # Add media files matching the search pattern to the process queue
  47. for n in files:
  48.   if expr.match (n): q.put(n)
  49.  
  50. # Spawn a seperate audio encoding process for each core
  51. for i in range (cores):
  52.   process = multiprocessing.Process(target=encodeAudio, args=())
  53.   process.start()
RAW Paste Data
Top