Converting *.wma to *.mp3 by SHELL-script with mplayer, lame, and find - bash

I want to convert my older *.wma files into *.mp3. For that purpose I found a short script to convert with using mplayer + lame (found here: https://askubuntu.com/questions/508625/python-v2-7-requires-to-install-plugins-to-play-media-files-of-the-following-t).
This works fine in a single directory. Now I wanted to improve it that way, that it's able to work with 'find'. Its intended to find a *.wma-file and then calling the script to convert that file to *.mp3.
Here is the script:
FILENAME=$1
FILEPATH="$(dirname $1)"
BASENAME="$(basename $1)"
mplayer -vo null -vc dummy -af resample=44100 -ao pcm:waveheader "$FILENAME"
lame -m j -h --vbr-new -b 320 audiodump.wav -o "`basename "$FILENAME" .wma`.mp3"
echo "Path: $FILEPATH" # just to see if its correct
echo "File: $BASENAME" # just to see if its correct
rm -f audiodump.wav
rm -f "$FILENAME"
At the moment I'm dealing with the issue, that the script put the converted *.mp3 in the directory which the console is working with (e.g. /home/user/ instead of /home/user/files/ where the *.wma comes from).
What can I do to let the script putting the new *.mp3 into the same directory as the *.wma?
If I want to use 'mv' within the script I get trouble with embedded spaces in the *.wma-filenames.
Thanks for any hints. I thought about setting the IFS to tab or newline, but I wounder if there is a better way to deal with this.

Here's something that uses ffmpeg for the conversion (after using ffprobe for figuring out what the bit_rate should be). It's based off of what I found in (https://askubuntu.com/questions/508278/how-to-use-ffmpeg-to-convert-wma-to-mp3-recursively-importing-from-txt-file). But I didn't have access to avprobe, so had to hunt for an alternative.
First navigate to the directory with all your files and run the following from your shell:
find . -type f | grep wma$ > wma-files.txt
Once that's done, you can put this into a script and run it:
#!/usr/bin/env bash
readarray -t files < wma-files.txt
ffprobe=<your_path_here>/ffprobe
ffmpeg=<your_path_here>/ffmpeg
for file in "${files[#]}"; do
out=${file%.wma}.mp3
bit_rate=`$ffprobe -v error -show_entries format=bit_rate -of default=noprint_wrappers=1:nokey=1 "$file"`
$ffmpeg -i "$file" -vn -ar 44100 -ac 2 -ab "$bit_rate" -f mp3 "$out"
done
This will save the mp3 files alongside the wma ones.

The problem is that basename is stripping both the .wma extension and the path leading to the file. And you only want the .wma stripping.
So the answer is not to use basename and instead just do the .wma stripping yourself (with Parameter Expansion).
outfile=${FILENAME%.wma}
lame -m j -h --vbr-new -b 320 audiodump.wav -o "$outfile.mp3"
(Note that I used lowercase $outfile. Generally $ALL_CAPS variables are reserved for the shell/terminal/environment and should be avoided in scripts.)

Related

Code must find all MP4 files within subdirectory to compress using ffmpeg

I have a drive with a lot of MP4 files which are tough to go through folder by folder and compress.
I'm trying to make a script that runs in terminal that will open a designated folder, find all .mp4 files in the subfolder, and compress the files using specs I designate with ffmpeg. Obviously, the output files should be much lower in size if done right. I'm drafting a code which I have an idea about below but I'm not too good with BASH and/or PERL.
for f in $(find ../ -iname '*.avi'); do
n=$(echo $f|sed -e 's/.avi/_cbr.mp4/i');
echo "ffmpeg [options] -i $f $n";
done
output:
ffmpeg [options] -i ../1hourjob/videncode/sound10s.avi ../1hourjob/videncode/sound10s_cbr.mp4
ffmpeg [options] -i ../1hourjob/videncode/t003.avi ../1hourjob/videncode/t003_cbr.mp4
ffmpeg [options] -i ../ffmpeg/Masha.avi ../ffmpeg/Masha_cbr.mp4
ffmpeg [options] -i ../ffmpeg/window.avi ../ffmpeg/window_cbr.mp4
I'm wondering if I can even make some sort of GUI for this too. I feel a bit lost.
You can recursively traverse the directories in bash like this:
avi_to_mp4() {
cd "$1"
for f in *; do
if [[ -d "$f" ]]; then
avi_to_mp4 "$f"
elif [[ "$f" == *.avi ]]; then
newf="${f:0: -4}.mp4"
echo "$f" to "$newf" # run your command here
fi
done
cd ..
}
avi_to_mp4 "$1"

Bash: loop ffmpeg command through sets of subfolders and direct it to files in the folders for processing

I am playing around with embedding captions into mp4 video files, and want to find a way to do this across large sets of directories with the .mp4 and .srt files in them. Each pair of .mp4 and .srt files will be subfoldered together in their own directory, and the basename should be the same between the two. Example:
Video1
Video1.mp4
Video1.srt
Video2
Video2.mp4
Video2.srt
I’ve tried several things but I’m a novice at this and only write very simple bash scripts for much more straightforward processes. For this I need to figure out how to write the bash script to run an ffmpeg command in every subfolder that will grab the mp4 and srt file and output a new mp4 of the merged data. The basic ffmpeg command to do this is:
ffmpeg -i filename.mp4 -i filename.srt -c copy -c:s mov_text output.mp4
I’ve tried to add:
for dir in ./*/; do ffmpeg -i *.mp4 -i *.srt -c copy -c:s move_text “$file”.mp4
…and several variations of this, but ffmpeg always stops with a “*.mp4: No such file or directory” error. Then I tried to add "for file in..." after the "for dir in" statement but didn't have any positive results. The following is closest to what I need - it at least goes to each folder and processes the files - but it does them independently and doesn't combine the mp4 and srt source files as the ffmpeg command should. It outputs a video.mp4.mp4 and video.srt.mp4, and fails to combine them in either case.
for dir in ./**/*;
do ffmpeg -i "$dir" -i "$dir" -c copy -c:s mov_text "$dir".mp4
I tried "$dir".mp4 and "$dir".srt but that just results in an error. I tried to pull just directory names:
for dir in ./**/*;
do ffmpeg -i "$(basename $dir)" -i "$(basename $dir)" -c copy -c:s mov_text "$dir".mp4
and my attempts using "$(basename $dir).extension" have resulted in errors - it looks for video.mp4.mp4 or video.srt.mp4. Any tips as to what to add to get this process to work or another approach entirely would be greatly appreciated! I figure it's a simple bash thing I'm just ignorant of, but certainly need to learn how to do! Thanks!
Run this within the dir containing Video1/, Video2/...
#!/bin/bash -e
shopt -s globstar
for v in ./**/*.mp4; do
s=${v%.*}.srt
if [ -f "$s" ]; then
ffmpeg -i "$v" -i "$s" -c copy -c:s mov_text "${v##*/}"
fi
done
./**/*.mp4 expands to ./Video1/Video1.mp4 ./Video1/Video2.mp4 ...,
${v%.*} removes the extension (./Video1/Video1.mp4 > ./Video1/Video1),
[ -f "$s" ] checks if $s (i.e. ./Video1/Video1.srt) exists,
${v##*/} extracts the basename of $v (./Video1/Video1.mp4 > Video1.mp4).
So the final structure of . will be like:
Video1.mp4 # subbed
Video1
Video1.mp4
Video1.srt
Video2.mp4 # subbed
Video2
Video2.mp4
Video2.srt
As a tweak to the excellent answer by ogizismail, the below is an approach that works with versions of bash too old to support globstar:
while IFS= read -r -d '' v; do
s=${v%.mp4}.srt
[[ -e $s ]] && ffmpeg -i "$v" -i "$s" -c copy -c:s mov_text "${v##*/}"
done < <(find . -mindepth 2 -name '*.mp4' -printf '%P\0')
The general technique is discussed in Using Find. Using -mindepth 2 stops it from finding your already-subbed output files.

Bash script that lists files in a directory doesn't work

I made a bash script because I need to convert a lot of files in a directory from .MOV to .mp4 format.
I created this script for the purpose:
#!/bin/bash
touch .lista
ls -1 "$1" | grep -i .MOV > .lista
list= `pwd`/.lista
cd "$1"
while read -r line;
do filename=${line%????}
ffmpeg -i "$line" -vcodec copy -acodec copy "$filename.mp4"; done < $list
rm .lista
This script is supposed to convert me each .MOV file into the directory indicated by $1, but it doesn't work, it converts me only one file, then it terminates. I can't understand why. What's wrong with that?
It's better to simply loop using globs:
for file in "$1"/*.MOV; do
ffmpeg -i "$file" ... "${file%.*}.mp4"
done
Why you shouldn't parse the output of ls.
Do them all fast and succinctly in parallel with GNU Parallel like this:
parallel --dry-run ffmpeg -i {} -vcodec copy -acodec copy {.}.mp4 ::: movies/*MOV
Sample Output
ffmpeg -i movies/a.MOV -vcodec copy -acodec copy movies/a.mp4
ffmpeg -i movies/b.MOV -vcodec copy -acodec copy movies/b.mp4
If that looks good, do it again but without --dry-run.
Note how easily GNU Parallel takes care of all the loops, all the quoting and changing the extension for you.
Your code is working for me. I cannot see any error. But I can suggest you a better approach. Don't use ls to get the filenames, it is not a good idea. Also, you can avoid changing dir.
#!/bin/bash
for line in $(find "$1" -maxdepth 1 -type f -iname "*.mov")
do
ffmpeg -i "$line" -vcodec copy -acodec copy "${line%????}.mp4"
done
You don't need to start by touching the file. In any case, you don't need a file at all, you can use a for loop to iterate over the files returned by find directly. With find, I'm already selecting all the files in the specified folder that have the expected extension.
Here I add a one-liner that should avoid problems with spaces:
find "$1" -maxdepth 1 -type f -iname "*.mov" -print0 | xargs -0 -n 1 -I{} bash -c "F={}; ffmpeg -i \"\$F\" -vcodec copy -acodec copy \"\${F%.*}\".mp4"

Convert files on directories that are not always there

I've got a script that runs when a torrent download is finished to see if there are FLAC audio files and if yes convert them to MP3. Until today I've used:
for file in "$torrentpath"/"$torrentname"/*.flac
do
ffmpeg -i "$file" -qscale:a 0 "${file[#]/%flac/mp3}"
done
But I realised that when a torrent comes containing sub-directories the script is useless. I've tried messing around for the past few days with "find" and "if" and other ways but I can't really see the answer. I know it's there.
The script should just test if there are sub-dirs and execute ffmpeg on those, otherwise directly go with the conversion.
Any little hint will be appreciated.
to handle arbitrary subdirectories in bash:
shopt -s globstar nullglob
for file in "$torrentpath/$torrentname"/**/*.flac
do ...
find "$torrentpath"/"$torrentname" -name '*.flac' -print | while read file; do
ffmpeg -i "$file" -qscale:a 0 "${file[#]/%flac/mp3}"
done

Bash Script to convert all flv file in a directory to mp3

This is my code so far.
#!/bin/bash
#James Kenaley
#Flv to Mp3 directory converter
find /home/downloads -iname "*.flv" | \
while read I;
do
`ffmpeg -i ${I} -acodec copy ${I/%.flv/.mp3}`
echo "$I has been converted"
done
but its picking up white spaces in the names of the flv files and throws a error saying its not in the directory. how do make it use the whole file name and not the just the first word before the space?
ffmpeg runs in forked threads, so simple batching can give weird behaviours. If you are running ffmpeg in the suggested batch loop, you should control your command and command-error output, so that it doesn't interfere.
If you run this and are getting every other item converted properly, but errors on the rest, try using this ffmpeg call in the loop:
ffmpeg -y -i "${I}" -acodec mp3 -ar 22050 -f wav "${I/%.3gp/.mp3}" > /dev/null & 2> /dev/null
Notice the > dev/null & 2> /dev/null on the end. This pipes the command output, and command error output into oblivion. Then the script works.
One should note too that the program output will look strangely disorganized, with multiple files compressing at the same time. The results will be correct.
[EDIT: NOTE THE -y THAT I HAVE, THIS MAKES FFMPEG OVERWRITE EXISTING MP3 FILES]
Try this:
`ffmpeg -i "${I}" -acodec copy "${I/%.flv/.mp3}"`
Use quotes. And don't use backquotes.
ffmpeg -i "${I}" -acodec copy "${I%.flv}".mp3
Either call a short script, to do conversion and renaming in one pass:
adhoc.sh:
$file="$1"
ffmpeg -i "$file" -acodec copy "${file/%.flv/.mp3}"
call it:
find /home/downloads -iname "*.flv" -exec ./adhoc.sh {} ";" -ls
or convert:
find /home/downloads -iname "*.flv" -exec ffmpeg -i {} -acodec copy {}.mp3 ";" -ls
and rename later:
rename 's/.flv.mp3/.mp3/' /home/downloads/*.flv.mp3
Rename is part of a perl package which might need installation.

Resources