Using FLAC decoder and LAME Encoder to convert FLAC files using Python - python

I am currently attempting to undergo a project to automate my music library cataloging using Python scripts, and I desperately need help before I go insane. For starters, I am using Linux (Arch Linux to be specific). To explain, I recently began using Morituri to rip my CD collection. I especially like the Mortituri script because it checks the files three times over, and generates FLAC files immediately.
This above system works fine, but I ran into another problem. I like FLAC files for my PC, but for mobile usage, I need MP3 files. I came across this famous little bash script:
for f in *.flac; do flac -cd "$f" | lame -b 320 - "${f%.*}".mp3; done
I saw this great little script, I knew there must be some way to replicate this in python. So I began working on a script that converts FLAC to MP3, and uses the basic arguments used by their respecitve CLI interfaces. I decided it be best to start with a single file at a time, and work my way up.After learning a bit about the subprocess module and pipes in python, I wrote the code below:
#!/usr/bin/python3
from subprocess import *
MyTestFile = ('/path/to/file.flac')
def Convert_It(File):
with open(File, 'r') as infile:
FlacDecode = Popen(["flac", "-cd","-","-"],stdin=infile,stdout=PIPE)
LameEncode = Popen(["lame", "-b", "192","-", "/a/differnet/path/test.mp3"],stdin=PIPE)
Convert_It(MyTestFile)
As it turns out, the output of this script is as follows:
flac 1.3.1, Copyright (C) 2000-2009 Josh Coalson, 2011-2014 Xiph.Org Foundation
flac comes with ABSOLUTELY NO WARRANTY. This is free software, and you are
welcome to redistribute it under certain conditions. Type `flac' for details.
-: ERROR while decoding metadata
state = FLAC__STREAM_DECODER_END_OF_STREAM
Warning: unsupported audio format
So I have a few questions:
Why is FLAC acting this way? In testing the script, I set to path to a real FLAC file. Why it say this?
How can I make this work?!
Really, any method using simple commands. Programs likes ffmpeg are not very easy to understand (how to set LAME q value to 0? No idea.) And other python scripts are way to long (like flac2all) for me to reverse engineer.
In review, any help is accepted. Just as long as it follows my specifications of: 1. only using the bare FLAC and LAME tools for linux (no sox or ffmpeg), 2. A script not too long. 3. Doesn't create a temporary WAV file. 4. Can encode any Flac file to MP3. I'm not even worried about metadata. Just the file itself.
Please HELP!
EDIT 08/05/2015:
I discovered I was using pipes incorrectly. Here is the code I created that solves my problem:
FlacDecode = subprocess.Popen(["flac","-cds",MyFile,"-"],stdout=subprocess.PIPE)
LameEncode = subprocess.Popen(['lame','-b','320','-'(NewFilePath)],stdin=FlacDecode.stdout,stdout=subprocess.PIPE)
EndLame = LameEncode.communicate()[0]

I had a similar problem, converting flac files to mp3, and found a one line bash solution here which reads:
for f in *.flac; do ffmpeg -i "$f" -aq 1 "${f%flac}mp3"; done
I appreciate that this doesn't answer the question but it is an elegant solution to your problem.

Related

Printing Automation using win32api Python [duplicate]

I'm correcting assignments from my students right now and I'd like to automate an annoying step I always have to do.
After annotating their PDF solutions, I need to Print them to PDF files in order to bake my annotations into the PDF so that they can be included in LaTeX. Right now I have to manually choose "Microsoft Print to PDF" and enter the PDFs name with a leading underscore (which is what my automatically generated LaTeX files expect). This gets annoying for 30+ files.
So I'd like to issue this in a batch-script automatically for all the PDFs to minimize my efforts to a simple double-click. I have seen that this is possible with e.g. C# (Here), but I'd like a solution with a simple batch script.
Can this be done?
Edit:
The C#-Code I found actually does not get the Job done. You can't print existing PDFs that way. I'd need to use Spire.PDF to do that. The Free Version however messes up the PDF; I can download the "Full" version in NuGet, this however generates a disclaimer at the beginning of any PDF, and it still can't handle things I draw in Adobe Reader DC. So C# really is not an option, I need a command-line solution.
You'll better install pdfcreator
and use the commandline options
I assume it should be quite easy using PowerShell, but I ran into the same problem as described in this post.
The PowerShell solution from here creates only blank PDF files for me.
There probably exist better solutions, but I managed to combine PDFtoPrinter and this post.
A batch script could look like this:
for /R %%f in (*.pdf) do (
(echo with createobject^("wscript.shell"^)
echo .run "<path to PDFtoPrinter.exe> ""%%f"""
echo wscript.sleep 3000
echo .sendkeys """%%~df%%~pf%%~nf_correction.pdf"""
echo .sendkeys "{enter}"
echo wscript.sleep 3000
echo end with) > %temp%\sk.vbs
start /w %temp%\sk.vbs
)
This script uses Microsoft Print to PDF to create corresponding files of the format <filename>_correction.pdf.
The batch script creates an sk.vbs script in %temp% and runs it.
The sk.vbs script then handles the file saving dialog of Microsoft Print to PDF.
Additionally, this solution has the drawback that you can't use your computer while the script runs because the sk.vbs script must send keys to the window in focus.

Python Ripping CD Files to WAV

I'm writing a program where I need to be able to rip files from a CD into WAV format (or flac but wav works fine). It must run on Windows. I saw other answers where Express Rip and Audio Commander were recommended as command line tools. But Audio Commander's page doesn't seem to exist anymore. And I'm not so sure about express rip, it seems a bit sketchy.
Then they mentioned mutagen for retrieving the metadata.
Anyone have any experience with these utilities or this goal? I would like to be able to rip a CD in WAV, keep the metadata that is there, and if possible check the CD Archive for metadata as well.
Anyone ever do anything like this or have an suggestions on modules, utilities, methods, etc. to get me going? Even some small examples would help. That is examples of ripping a cd with python, or modules to accomplish the task.
You might want to have a look at PyMedia
PyMedia is a Python module for wav, mp3, ogg,
avi, divx, dvd, cdda etc files manipulations. It allows you to parse,
demutiplex, multiplex, decode and encode all supported formats. It can
be compiled for Windows, Linux and cygwin.
PyMedia was built to be really simple and flexible at the same time.
See tutorial for example. It allows you to create your own multimedia
applications in a matter of minutes and adjust it to your needs using
other components. Python language is chosen because of simple
semantics, complete and reach set of features.
You can also use this as a library:
From their Audio CD Grabber:
import pymedia.removable.cd as cd
def readTrack(track, offset, bytes):
cd.init()
if cd.getCount() == 0:
print 'There is no cdrom found. Bailing out...'
return 0
c = cd.CD(0)
props = c.getProperties()
if props['type'] != 'AudioCD':
print 'Media in %s has type %s, not AudioCD. Cannot read audio data.' % (c.getName(), props['type'])
return 0
tr0 = c.open(props['titles'][track - 1]['name'])
tr0.seek(offset, cd.SEEK_SET)
return tr0.read(bytes)
Update: For accessing metadata about the Audio CD you can use the PyCDDB lirbary.

Python split mp3 channel

I'd like to seperate the channels of a mp3 file in Python and save it in two other files.
Does anybody know a library for this.
Thanks in advance.
I assume you want to split the channels losslessly, without decoding MP3 and re-encoding it - otherwise you would not have mentioned MP3 at all and would have easily found many tools like Audacity to do that.
There are 4 channel modes of MP3 frames - this means 4 types of MP3 files: simple stereo, joint-stereo, dual-channel, mono. joint-stereo files can't be split without loss. mono files doesn't need splitting. The rest: stereo and dual-channel, consists of less than 0.1% of all MP3 files, technically can be split into 2 files, each for a channel, without loss. However there is not any tool on the Internet to do that - not any command line tool nor any GUI tool, because few need the function.
There are not any python library for you neither. Most libraries abstracted MP3 files into a common audio which you can manipulate, after decoding. pymad is the only one specific to MP3 file, and it can tell if a file is using any of the 4 channel modes, but does not offer to extract a channel without decoding it. If you write a new tool, you will have to work on raw MP3 files or produce a library for it.
And it is not easy to write a tool or library for it. It's one stream with 2 channels and not two streams interleaved on a frame level. You cannot simply work on MP3 frames, drop some frames, keep others, and manage to extract a channel out that way. It's a task for a professional, and perhaps best happen in a decoder project (like lame or libmad) and not in a file manipulation project (like mp3info or the python eyeD3). In other words, this feature is likely written in C, not python.
Implementaiton Note:
The task to build such a tool thus suits well for a computer science C-programming language course project:
1. it takes a lot of time to do;
2. it requires every skill learned from C programming course;
3. it can get wrong easily;
4. it is likely built on the work of other projects, a lesson of adaptating existing work;
5. is a damn-hard endeavor that no-one did before and thus very rewarding
6. perhaps can be done in 300 difficult lines of code instead of bloated simple Visual Basic code, thus is a good lession of modesty and quality;
7. and finally: nobody is waiting in an hurry for a working implementation.
All condition fits perfectly for a C-programming course project.
Implementation Note 2:
some bit-rates are only possible in mono mode (80kbps), and some bit-rates are only possible in stereo mode (e.g. 320kpbs). Luckily this does not present a problem in this task, because all dual-mp3 bit-rate can be mapped into a fitting mono-mp3 bit-rate -- but not vice versa!

Python Audio Edit

I am searching for a way to write a simple python
program to perform an automatic edit on an audio file.
I wrote with PIL automatic picture resizing to a predefined size.
I would like to write the same for automatic file re-encoding into a predefined bitrate.
similarly, i would like to write a python program that can stretch an audio file and re-encode it.
do i have to parse MP3's by myself, or is there a library that can be used for this?
Rather than doing this natively in Python, I strongly recommend leaving the heavy lifting up to FFMPEG, by executing it from your script.
It can chop, encode, and decode just about anything you throw at it. You can find a list of common parameters here: http://howto-pages.org/ffmpeg/
This way, you can leave your Python program to figure out the logic of what you want to cut and where, and not spend a decade writing code to deal with all of the audio formats available.
If you don't like the idea of directly executing it, there is also a Python wrapper available for FFMPEG.
There is pydub. It's an easy to use library.

How to programatically combine two aac files into one?

I'm looking for a cat for aac music files (the stuff iTunes uses).
Use Case: My father in law will not touch computers except for audiobooks he downloads to his iPod. I have taught him some iTunes (Windows) basics, but his library is a mess. It turns out, that iTunes is optimized for listening to podcasts and random songs from your library, not for audiobooks.
I would like to write a script (preferably python, but comfortable with other stuff too) to import his audiobook cds in a sane fashion, combining the tracks of each cd into a bookmarkable aac file (.m4b?) and then adding that to iTunes so it shows up in the audiobooks section.
I have figured out how to talk to iTunes (there is a COM interface in Windows, look for the iTunes SDK). Using that interface, I can use iTunes to rip the CD to aac format. It's the actual concatenation of the aac files I'm having trouble with. Can't find the right stuff on the net...
I created a freeware program called "Chapter and Verse" to concatenate m4a (AAC) files into a single m4b audiobook file with chapter marks and metadata.
If you have already ripped the CD's to AAC using itunes (which you say you have) then the rest is easy with my software. I wrote it for this exact reason and scenario. You can download it from www.lodensoftware.com
After trying to work with SlideShow Assembler, the QT SDK and a bunch of other command line tools, I ended up building my own application based on the publicly available MP4v2 library. The concatenating of files and adding of chapters is done using the MP4v2 library.
There are quite a few nuances in building an audiobook properly formatted for the iPod. The information is hard to find. Working with Apple documentation and open libraries has its own challenges as well.
Best of Luck.
Not programming related (well, kinda.)
iTunes already has functionality to rip as a single track (e.g. an audiobook.) Check this out: http://www.ehow.com/how_2108906_merge-cd-single-track-itunes.html
That fixes your immediate problem, but I guess people can keep discussing how to do it programatically.
The most powerful Python audio manipulation module out there seems to be Python Audio Tools. The download comes with CLI tools that would probably do everything you'd want to do, even ripping, so you can even get by with shell scripting the whole thing. The module itself is also pretty powerful and has a handy set of functions to manipulate audio files. If you want to stick with writing everything in python, you can possibly learn enough to do what you want to do after studying their CLI source code. Specifically they have a tool that just does audio file cat in any codec. (They do depend on FAAC/FAAD2 for AAC support, but that'd be true for every library you'll find)
I haven't seen an aac codec library for python, but you could use wav files as an intermediary format.
You can pull the tracks off the cd as wav files, and then use the wave module to concatenate them into one large file, which could then be converted by itunes to aac. This may increase your processing time considerably because of the size of the data, but it would be fairly easy, and you don't need any external libraries.

Categories

Resources