2013年4月29日月曜日

ffmepgコマンドでmp4の動画からm4a(音声)を抜き出してみた

ffmpegコマンドでmp4からm4a音声データだけを抜き出す


中学時代の同級生から電話があり、何かと思ったら

「区民大会で使うBGMが欲しいのだけどどうにかならない? CDとか作り方分からないし...」

それは困った...けど俺もやりたくないし、やり方が分からない。
地元の区民大会にも「必ず出るように!」と町内の先輩から念を押されているので、「そんなこと、嫌です」なんて言えないし。

「了解しました、やりましょう」ということ引き受けてしまい、さらに悪いことに、
Windows8でやろうと思ったのですが、操作方法が難しいのでGentooでやってみました

まず、youtubeで適当にmp4を拾ってくる


これはブラウザで拾ってきてね

次にffmpegパッケージをインストールする


USEフラグはaacを入れてください、自分はこんな感じです
karky7 ~ # equery u media-video/ffmpeg 
[ Legend : U - final flag setting for installation]
[        : I - package is installed with flag     ]
[ Colors : set, unset                             ]
 * Found these USE flags for media-video/ffmpeg-0.10.7:
 U I
 - - 3dnow                : Adds support for 3dnow multimedia processor instructions
 - - 3dnowext             : Enable manually-optimised routines using the AMD 3DNow!Ex SIMD instruction set, present in modern AMD CPUs. (Check for 3dnowext in
                            /proc/cpuinfo to know whether your CPU supports it). 
 + + X                    : Adds support for X11
 + + aac                  : Enables support for MPEG-4 AAC Audio
 - - aacplus              : AAC+ encoding via media-libs/libaacplus.
 + + alsa                 : Adds support for media-libs/alsa-lib (Advanced Linux Sound Architecture)
 - - amr                  : Enables Adaptive Multi-Rate Audio support
 - - avx                  : Adds support for Advanced Vector Extensions instructions (Intel Sandy Bridge, AMD Bulldozer and later chips)
 - - bindist              : Enforces license compatibility constraints via REQUIRED_USE.
 + + bzip2                : Use the bzlib compression library
 - - cdio                 : Enables audio CD grabbing with dev-libs/libcdio.
 - - cpudetection         : Enables runtime CPU detection (useful for bindist, compatibility on other CPUs)
 - - debug                : Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see
                            http://www.gentoo.org/proj/en/qa/backtraces.xml
 - - dirac                : Enable Dirac video support (an advanced royalty-free video compression format) via the reference library: dirac.
 + + doc                  : Adds extra documentation (API, Javadoc, etc). It is recommended to enable per package instead of globally
 + + encode               : Adds support for encoding of audio or video files
 - - faac                 : Use external faac library for AAC encoding
 + - fftools_aviocat      : cat's an URL to another one, useful for dumping streams.
 + - fftools_cws2fws      : converts cws files (Macromedia Flash, compressed) to fws ones (Macromedia Flash, uncompressed).
 + - fftools_ffeval       : A simple expression evalutor.
 + - fftools_graph2dot    : A tool to convert a libavfilter graph to a dot file.
 + - fftools_ismindex     : A tool for creating smooth streaming manifests.
 + - fftools_pktdumper    : Dumps packets as demuxed by libavformat.
 + - fftools_qt-faststart : Rearranges a Quicktime file to facilitate network streaming.
 + - fftools_trasher      : Writes burts of random data into a file. Great for testing error robustness/resilience/concealment.
 - - frei0r               : Enable frei0r wrapping in libavfilter
 - - gnutls               : Adds support for net-libs/gnutls (TLS 1.0 and SSL 3.0 support)
 - - gsm                  : Adds support for the gsm lossy speech compression codec
 + - hardcoded-tables     : Use pre-calculated tables rather than calculating them on the fly.
 - - ieee1394             : Enable FireWire/iLink IEEE1394 support (dv, camera, ...)
 - - jack                 : Adds support for the JACK Audio Connection Kit
 - - jpeg2k               : Support for JPEG 2000, a wavelet-based image compression format
 - - libass               : SRT/SSA/ASS (SubRip / SubStation Alpha) subtitle support
 - - libv4l               : Uses media-libs/libv4l for video4linux instead of direct calls. Adds support for more devices via the userspace library.
 + + mmx                  : Adds support for optimizations for Pentium MMX and Athlon class processors
 - - mmxext               : Enables mmx2 support
 - - modplug              : Adds libmodplug support for playing SoundTracker-style music files
 + + mp3                  : Add support for reading mp3 files
 - - network              : Enables network streaming support
 - - openal               : Adds support for the Open Audio Library
 - - openssl              : Enables dev-libs/openssl support. Adds support for encrypted network protocols (TLS/HTTPS).
 - - oss                  : Adds support for OSS (Open Sound System)
 - - pic                  : Force shared libraries to be built as PIC (this is slower)
 + + pulseaudio           : Adds support for PulseAudio sound server
 - - rtmp                 : Enable Real Time Messaging Protocol using librtmp
 - - schroedinger         : Enable Dirac video support (an advanced royalty-free video compression format) via libschroedinger (high-speed implementation in C of the
                            Dirac codec).
 + + sdl                  : Adds support for Simple Direct Layer (media library)
 - - speex                : Adds support for the speex audio codec (used for speech)
 - - ssse3                : Faster floating point optimization for SSSE3 capable chips (Intel Core 2 and later chips)
 - - static-libs          : Build static libraries
 - - test                 : Workaround to pull in packages needed to run with FEATURES=test. Portage-2.1.2 handles this internally, so don't set it in
                            make.conf/package.use anymore
 - - theora               : Adds support for the Theora Video Compression Codec
 - - threads              : Adds threads support for various packages. Usually pthreads
 + + truetype             : Adds support for FreeType and/or FreeType2 fonts
 - - v4l                  : Enable support for video4linux (using linux-headers or userspace libv4l libraries)
 - - vaapi                : Enables VAAPI (Video Acceleration API) for hardware decoding
 - - vdpau                : Enable the Video Decode and Presentation API for Unix acceleration interface
 + + vorbis               : Adds support for the OggVorbis audio codec
 - - vpx                  : Enables vp8 codec support using libvpx: Decoding vp8 does not require this to be enabled but libvpx can also be used for decoding; encoding
                            vp8 requires this useflag to be enabled though.
 + + x264                 : Enable h264 encoding using x264
 + + xvid                 : Adds support for xvid.org's open-source mpeg-4 codec
 + + zlib                 : Adds support for zlib (de)compression
karky7 ~ # 

次にffmpegパッケージをインストールする


USEフラグを決めたらffmpegパッケージのインストール
karky7 ~ # emerge -pv media-video/ffmpeg 

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild     U  ] media-video/ffmpeg-0.10.7 [0.10.3] USE="X aac alsa bzip2 doc encode hardcoded-tables mmx mp3 pulseaudio sdl truetype vorbis x264 xvid zlib -3dnow -3dnowext -aacplus (-altivec) -amr -avx -bindist -cdio (-celt) -cpudetection -debug -dirac -faac -frei0r -gnutls -gsm -ieee1394 -jack -jpeg2k -libass -libv4l -mmxext -modplug (-neon) -network -openal -openssl -oss -pic -rtmp -schroedinger -speex -ssse3 -static-libs {-test} -theora -threads -v4l -vaapi -vdpau (-vis) -vpx" FFTOOLS="aviocat cws2fws ffeval graph2dot ismindex pktdumper qt-faststart trasher" 5,647 kB

Total: 1 package (1 upgrade), Size of downloads: 5,647 kB

 * IMPORTANT: 1 news items need reading for repository 'hacking-gentoo'.
 * IMPORTANT: 13 news items need reading for repository 'gentoo'.
 * Use eselect news to read news items.

karky7 ~ # emerge media-video/ffmpeg

ffmpegをコマンドから使ってみる

こんな感じで変換できる、とりあえずffmpeg --helpしても膨大なヘルプが出てくるので後で確認してください

オプションの説明
  • -i
    • inputファイル
  • -nv
    • 音声のみ抽出(disable video) 
  • -acodec copy
    •  force audio codec ('copy' to copy stream)

と言うような感じで、抜き出す

cuomo@karky7 ~/m4a $ ffmpeg -i ニンジャリバンバンキャリーパミュパミュ.mp4 -vn -acodec copy ニンジャリバンバンキャリーパミュパミュ.m4a
ffmpeg version 0.10.7 Copyright (c) 2000-2013 the FFmpeg developers
  built on Apr 29 2013 16:33:56 with gcc 4.5.4
  configuration: --prefix=/usr --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --enable-shared --cc=x86_64-pc-linux-gnu-gcc --cxx=x86_64-pc-linux-gnu-g++ --ar=x86_64-pc-linux-gnu-ar --optflags='-mtune=native -O2 -pipe' --extra-cflags='-mtune=native -O2 -pipe' --extra-cxxflags='-mtune=native -O2 -pipe' --disable-static --enable-gpl --enable-version3 --enable-postproc --enable-avfilter --disable-stripping --disable-debug --disable-network --disable-vaapi --disable-vdpau --enable-libmp3lame --enable-libvo-aacenc --enable-libvorbis --enable-libx264 --enable-libxvid --disable-indev=v4l --disable-indev=v4l2 --disable-indev=oss --disable-indev=jack --enable-x11grab --enable-libpulse --disable-outdev=oss --enable-libfreetype --disable-amd3dnow --disable-amd3dnowext --disable-altivec --disable-avx --disable-mmx2 --disable-ssse3 --disable-vis --disable-neon --cpu=host --enable-hardcoded-tables
  libavutil      51. 35.100 / 51. 35.100
  libavcodec     53. 61.100 / 53. 61.100
  libavformat    53. 32.100 / 53. 32.100
  libavdevice    53.  4.100 / 53.  4.100
  libavfilter     2. 61.100 /  2. 61.100
  libswscale      2.  1.100 /  2.  1.100
  libswresample   0.  6.100 /  0.  6.100
  libpostproc    52.  0.100 / 52.  0.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'ニンジャリバンバンキャリーパミュパミュ.mp4':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: isommp42
    creation_time   : 2013-04-08 12:52:24
  Duration: 00:04:24.31, start: 0.000000, bitrate: 725 kb/s
    Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 640x360, 626 kb/s, 23.98 fps, 23.98 tbr, 48k tbn, 47.95 tbc
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (mp4a / 0x6134706D), 44100 Hz, stereo, s16, 96 kb/s
    Metadata:
      creation_time   : 2013-04-08 12:52:25
      handler_name    : 
Output #0, ipod, to 'ニンジャリバンバンキャリーパミュパミュ.m4a':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: isommp42
    creation_time   : 2013-04-08 12:52:24
    encoder         : Lavf53.32.100
    Stream #0:0(und): Audio: aac (mp4a / 0x6134706D), 44100 Hz, stereo, 96 kb/s
    Metadata:
      creation_time   : 2013-04-08 12:52:25
      handler_name    : 
Stream mapping:
  Stream #0:1 -> #0:0 (copy)
Press [q] to stop, [?] for help
size=    3143kB time=00:04:24.31 bitrate=  97.4kbits/s    
video:0kB audio:3098kB global headers:0kB muxing overhead 1.460185%
cuomo@karky7 ~/m4a $

一つ一つコマンドを打つのは面倒なのでhaskellで片付ける


頑張ってhaskellで変換スクリプトをシコシコ作ってみました
第1引数にmp4のファイルがあるディレクトリを指定すると全部をm4aファイルに変換する優れものです
import System.Directory
import System.Environment (getArgs)
import System.Posix
import Control.Monad (forM, filterM)
import System.Process
import Data.List.Split
import System.Exit

main :: IO()
main = do
  path <- getPath
  fs <- getDirectoryContents path
  fullpath <- filterM isFile $ map (\filepath -> path ++ filepath) fs
  _ <- forM fullpath (\file ->
                   do (exitCode, stdout, stderr) <- readProcessWithExitCode "ffmpeg" (createArg file) []
                      case exitCode of
                        ExitFailure _ -> putStrLn stderr >> exitFailure
                        _ -> putStrLn $ "Convert OK: " ++ file)
  putStrLn "Complete."

getPath :: IO String
getPath = do
  path <- getArgs
  return (head path)


createArg :: FilePath -> [String]
createArg fname = case splitOn "." fname of
  [file, _] -> ["-i" , fname, "-vn", "-acodec", "copy", file ++ ".m4a"]
  _ -> []

isFile :: FilePath -> IO Bool
isFile file = getFileStatus file >>= (\fs -> return $ not $ isDirectory fs)
実行結果すると、こんな感じです
cuomo@karky7 ~ $ runhaskell convert.hs ~/mp4/
Convert OK: /home/cuomo/mp4/そのまま東へ-ファンモン.mp4
Convert OK: /home/cuomo/mp4/晴伝説-湘南乃風.mp4
Convert OK: /home/cuomo/mp4/虹-福山雅治.mp4
Convert OK: /home/cuomo/mp4/キセキ-GReeeeN.mp4
Convert OK: /home/cuomo/mp4/ワイルトアットハート-嵐.mp4
Convert OK: /home/cuomo/mp4/夏色-ゆす.mp4
Convert OK: /home/cuomo/mp4/ヘヒーローテーション-AKB48.mp4
Convert OK: /home/cuomo/mp4/JAMBOREE!!-AAA.mp4
Convert OK: /home/cuomo/mp4/あの紙ヒコーキくもり空わって-19.mp4
Convert OK: /home/cuomo/mp4/女々しくて-ゴールデンボンバー.mp4
Convert OK: /home/cuomo/mp4/栄光の架け橋-ゆず.mp4
Convert OK: /home/cuomo/mp4/PartyItUp-AAA.mp4
Convert OK: /home/cuomo/mp4/パンダヒーロー-初音ミク.mp4
Convert OK: /home/cuomo/mp4/走れ-ももいろクローバー.mp4
Convert OK: /home/cuomo/mp4/つけまつける-きゃりーぱみゅぱみゅ.mp4
Convert OK: /home/cuomo/mp4/PONPONPON-きゃりーぱみゅぱみゅ.mp4
Convert OK: /home/cuomo/mp4/あなたに-MONGOL800.mp4
Convert OK: /home/cuomo/mp4/にんじゃりばんばん-きゃりーぱみゅぱみゅ.mp4
Convert OK: /home/cuomo/mp4/Sunny Day Sunday-センチメンタル・バス.mp4
Convert OK: /home/cuomo/mp4/JOINT-RIPSLYME.mp4
Convert OK: /home/cuomo/mp4/ウルトラソウル-Bz.mp4
Convert OK: /home/cuomo/mp4/楽園ベイベー-RipSlyme.mp4
Convert OK: /home/cuomo/mp4/夢叶う-MONGOL800.mp4
Convert OK: /home/cuomo/mp4/高架線-ELLEGARDEN.mp4
Convert OK: /home/cuomo/mp4/ロコローション-オレンジレンジ.mp4
Convert OK: /home/cuomo/mp4/世界はそれを愛と呼ぶんだぜ-サンボマスター.mp4
Convert OK: /home/cuomo/mp4/日曜日よりの使者.mp4
Convert OK: /home/cuomo/mp4/マトリョシカ-初音ミク.mp4
Convert OK: /home/cuomo/mp4/SPARK-三代目.mp4
Convert OK: /home/cuomo/mp4/Sabotage-Beastie Boys.mp4
Convert OK: /home/cuomo/mp4/以心電信-オレンジレンジ.mp4
Convert OK: /home/cuomo/mp4/マツケンサンバII.mp4
Convert OK: /home/cuomo/mp4/Monster-嵐.mp4
Convert OK: /home/cuomo/mp4/フライングゲット-AKB48.mp4
Convert OK: /home/cuomo/mp4/爆音男-湘南乃風.mp4
Complete.
cuomo@karky7 ~ $ 
こんな感じでm4aファイルができあがる、Shellスクリプトで書いた方が早いような気がしますが...笑 ^^;

抜いたm4aがMacで聞けるか試してみる


これをMacで聞いてみる、と


ニンジャリバンバン、松ケンとか、聞けてる、とりあえずこれでOK、区民大会はGentoo >>= Macな音楽転送で何とかなりそうです。

0 件のコメント:

コメントを投稿