這篇文章,分成4個重點,取得/轉換/剪接/合併,還有分享如何幫mp3 檔案增加封面圖片。
最好的解法,還是使用有瀏覽器+擋廣告功能,在google 使用關鍵字:youtube mp3 download ,建議使用 yt1s 提供的服務來下載 mp3.
1:取得youtube 上的影片
透過 youtube-dl 指令,可以取得 youtube 上的影片。
2:轉換 youtube 上的影片為 mp3
這個功能,除了可以使用 youtube-dl 指令,一次直取得並轉換之外,如果你想要手機上取得youtube 上的影片為mp3, 也可以使用很多免費的網站,有提供線上下載的服務。
先在手機的YouTube 的官方 app 裡去輸入關鍵字,找到想要的歌曲或合輯。
再使用手機瀏覽器,在google 輸入關鍵字 youtube mp3 去查,然後在任一個查出來的網頁裡的輸入框裡貼上剛才YouTube 的網址,就可以開始轉換(或下載)該首歌的mp3 檔案在手機裡。
建議使用brave 瀏覽器來操作,會比較不會看到廣告,也可以使用brave瀏覽器去YouTube 網站,brave 瀏覽器除了可以背景播放音樂之外,而且還不會有廣告,超讚的!
透過手機備份自己所拍攝的影片很方便,如果想在電腦裡下載自己行上的影片,可以透過外部指令 youtube-dl + youtube 網址即可下載到自己上傳的影片,進而可以剪輯影片內容。
youtube-dl的指令,也可以把「自己上傳」到網路上的影片轉成 mp3:
youtube-dl -x --no-check-certificate --audio-format mp3 -f 'bestaudio[ext=m4a]' --embed-thumbnail --no-check-certificate <video URL>
如果覺得上面指令太長,就寫一個 shell script(批次檔)如下:
Mac OS/Linux:
#!/bin/bash youtube-dl -x --no-check-certificate --audio-format mp3 -f 'bestaudio[ext=m4a]' --embed-thumbnail --no-check-certificate
Windows
@youtube-dl -x --no-check-certificate --audio-format mp3 -f 'bestaudio[ext=m4a]' --embed-thumbnail --no-check-certificate %1
Linux 之下,要記得執行:
chmod +x dl.sh
這樣子,檔案才能被執行。
youtube-dl 的關於解碼聲音的說:
Post-processing Options: -x, --extract-audio Convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe) --audio-format FORMAT Specify audio format: "best", "aac", "flac", "mp3", "m4a", "opus", "vorbis", or "wav"; "best" by default; No effect without -x --audio-quality QUALITY Specify ffmpeg/avconv audio quality, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default 5)
建議的作法:(以 Mac OS X 為例)
1: 安裝 youtube-dl
https://rg3.github.io/youtube-dl/download.html
brew install youtube-dl
使用方法:
youtube-dl + URL
附註:
youtube-dl 比你想像中的還強,除了可以備份自己上傳到 youtube 或 facebook 之外,你所上傳到其他知名「影音」網站上公開的影片都可以備份下載。
2:安裝 ffmpeg
https://www.ffmpeg.org/download.html
brew install ffmpeg
使用方法:
ffmpeg -i input.mp4 output.mp3
附註:由於 ffmpeg 和 youtube 定前都會更新版本,所以建議遇到有問題的時候,先升級到最新版本試看看,更新方法:
brew update brew upgrade
錯誤排除的方法,如果遇到顯示這個錯誤:
[debug] ffmpeg command line: ffprobe -show_streams ‘file:The Chainsmokers 老菸槍 & Coldplay 酷玩樂團 _. Something Just Like This 如此而已 中文字幕-WslMtygxznQ.mp4’
ERROR: WARNING: unable to obtain file audio codec with ffprobe
請先下指令:
youtube-dl -v -x URL
透過-v 參數來輸出 debug 資訊,可以看到實際下載的影片網址,結果點進去,真的就沒有聲音的版本,所以透過下列的指令,也無法把youtube-dl 下載下來的 mp4 轉成 mp3:
ffmpeg -i 檔名.mp4 檔名.mp3
如果想知道,youtube 上面提供了那一些的格式,可以使用指令:
youtube-dl -x --no-check-certificate -F URL
結果:
[info] Available formats for WslMtygxznQ: format code extension resolution note 249 webm audio only DASH audio 60k , opus @ 50k, 1.47MiB 250 webm audio only DASH audio 78k , opus @ 70k, 1.95MiB 140 m4a audio only DASH audio 128k , m4a_dash container, mp4a.40.2@128k, 3.75MiB 394 mp4 audio only 144p 134k , 30fps, 1.80MiB 171 webm audio only DASH audio 137k , vorbis@128k, 3.78MiB 251 webm audio only DASH audio 144k , opus @160k, 3.83MiB 395 mp4 audio only 240p 152k , 30fps, 1.72MiB 396 mp4 audio only 360p 252k , 30fps, 2.97MiB 397 mp4 audio only 480p 391k , 30fps, 4.93MiB 398 mp4 audio only 720p 772k , 30fps, 11.77MiB 160 mp4 256x144 144p 41k , avc1.4d400c, 30fps, video only, 859.74KiB 278 webm 256x144 144p 91k , webm container, vp9, 30fps, video only, 2.19MiB 133 mp4 426x240 240p 95k , avc1.4d4015, 30fps, video only, 1.80MiB 242 webm 426x240 240p 119k , vp9, 30fps, video only, 2.29MiB 134 mp4 640x360 360p 188k , avc1.4d401e, 30fps, video only, 3.71MiB 243 webm 640x360 360p 213k , vp9, 30fps, video only, 4.06MiB 244 webm 854x480 480p 309k , vp9, 30fps, video only, 6.18MiB 135 mp4 854x480 480p 317k , avc1.4d401f, 30fps, video only, 6.04MiB 136 mp4 1280x720 720p 594k , avc1.4d401f, 30fps, video only, 10.78MiB 247 webm 1280x720 720p 601k , vp9, 30fps, video only, 10.37MiB 18 mp4 640x360 medium , avc1.42001E, mp4a.40.2@ 96k, 10.63MiB (best)
可以發現,畫質最佳的 1280×720 webm 格式是沒有聲音的,也是造成預設參數的情況下,取得無聲影片的結果。
-F 會列出所以格式(format code),-f 是去下載特定的格式。如果想要下載特定的格式。
.mp3 轉成 .amr
透過 ffmpeg 也可以把聲音轉換為 .amr 格式。
The Adaptive Multi-Rate (AMR) codec is an audio compression format enhanced for speech coding.
https://en.wikipedia.org/wiki/Adaptive_Multi-Rate_audio_codec
只是透過 ffmpeg 所轉換的 .amr sample rate “只有” 8000, 音質快吐血,而且只支援單聲道。轉成 .amr 的指令:
ffmpeg -i mfile.mp3 -ar 8000 -ac 1 audio.amr
下面是 youtube-dl 的官方英文說明:
FORMAT SELECTION
By default youtube-dl tries to download the best available quality, i.e. if you want the best quality you don’t need to pass any special options, youtube-dl will guess it for you by default.
But sometimes you may want to download in a different format, for example when you are on a slow or intermittent connection. The key mechanism for achieving this is so-called format selection based on which you can explicitly specify desired format, select formats based on some criterion or criteria, setup precedence and much more.
The general syntax for format selection is --format FORMAT
or shorter -f FORMAT
where FORMAT
is a selector expression, i.e. an expression that describes format or formats you would like to download.
tl;dr: navigate me to examples.
The simplest case is requesting a specific format, for example with -f 22
you can download the format with format code equal to 22. You can get the list of available format codes for particular video using --list-formats
or -F
. Note that these format codes are extractor specific.
You can also use a file extension (currently 3gp
, aac
, flv
, m4a
, mp3
, mp4
, ogg
, wav
, webm
are supported) to download the best quality format of a particular file extension served as a single file, e.g. -f webm
will download the best quality format with the webm
extension served as a single file.
You can also use special names to select particular edge case formats:
best
: Select the best quality format represented by a single file with video and audio.worst
: Select the worst quality format represented by a single file with video and audio.bestvideo
: Select the best quality video-only format (e.g. DASH video). May not be available.worstvideo
: Select the worst quality video-only format. May not be available.bestaudio
: Select the best quality audio only-format. May not be available.worstaudio
: Select the worst quality audio only-format. May not be available.
For example, to download the worst quality video-only format you can use -f worstvideo
.
If you want to download multiple videos and they don’t have the same formats available, you can specify the order of preference using slashes. Note that slash is left-associative, i.e. formats on the left hand side are preferred, for example -f 22/17/18
will download format 22 if it’s available, otherwise it will download format 17 if it’s available, otherwise it will download format 18 if it’s available, otherwise it will complain that no suitable formats are available for download.
If you want to download several formats of the same video use a comma as a separator, e.g. -f 22,17,18
will download all these three formats, of course if they are available. Or a more sophisticated example combined with the precedence feature: -f 136/137/mp4/bestvideo,140/m4a/bestaudio
.
You can also filter the video formats by putting a condition in brackets, as in -f "best[height=720]"
(or -f "[filesize>10M]"
).
The following numeric meta fields can be used with comparisons <
, <=
, >
, >=
, =
(equals), !=
(not equals):
filesize
: The number of bytes, if known in advancewidth
: Width of the video, if knownheight
: Height of the video, if knowntbr
: Average bitrate of audio and video in KBit/sabr
: Average audio bitrate in KBit/svbr
: Average video bitrate in KBit/sasr
: Audio sampling rate in Hertzfps
: Frame rate
Also filtering work for comparisons =
(equals), ^=
(starts with), $=
(ends with), *=
(contains) and following string meta fields:
ext
: File extensionacodec
: Name of the audio codec in usevcodec
: Name of the video codec in usecontainer
: Name of the container formatprotocol
: The protocol that will be used for the actual download, lower-case (http
,https
,rtsp
,rtmp
,rtmpe
,mms
,f4m
,ism
,http_dash_segments
,m3u8
, orm3u8_native
)format_id
: A short description of the format
Any string comparison may be prefixed with negation !
in order to produce an opposite comparison, e.g. !*=
(does not contain).
Note that none of the aforementioned meta fields are guaranteed to be present since this solely depends on the metadata obtained by particular extractor, i.e. the metadata offered by the video hoster.
Formats for which the value is not known are excluded unless you put a question mark (?
) after the operator. You can combine format filters, so -f "[height <=? 720][tbr>500]"
selects up to 720p videos (or videos where the height is not known) with a bitrate of at least 500 KBit/s.
You can merge the video and audio of two formats into a single file using -f <video-format>+<audio-format>
(requires ffmpeg or avconv installed), for example -f bestvideo+bestaudio
will download the best video-only format, the best audio-only format and mux them together with ffmpeg/avconv.
Format selectors can also be grouped using parentheses, for example if you want to download the best mp4 and webm formats with a height lower than 480 you can use -f '(mp4,webm)[height<480]'
.
Since the end of April 2015 and version 2015.04.26, youtube-dl uses -f bestvideo+bestaudio/best
as the default format selection (see #5447, #5456). If ffmpeg or avconv are installed this results in downloading bestvideo
and bestaudio
separately and muxing them together into a single file giving the best overall quality available. Otherwise it falls back to best
and results in downloading the best available quality served as a single file. best
is also needed for videos that don’t come from YouTube because they don’t provide the audio and video in two different files. If you want to only download some DASH formats (for example if you are not interested in getting videos with a resolution higher than 1080p), you can add -f bestvideo[height<=?1080]+bestaudio/best
to your configuration file. Note that if you use youtube-dl to stream to stdout
(and most likely to pipe it to your media player then), i.e. you explicitly specify output template as -o -
, youtube-dl still uses -f best
format selection in order to start content delivery immediately to your player and not to wait until bestvideo
and bestaudio
are downloaded and muxed.
If you want to preserve the old format selection behavior (prior to youtube-dl 2015.04.26), i.e. you want to download the best available quality media served as a single file, you should explicitly specify your choice with -f best
. You may want to add it to the configuration file in order not to type it every time you run youtube-dl.
Format selection examples
Note that on Windows you may need to use double quotes instead of single.
# Download best mp4 format available or any other best if no mp4 available $ youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' # Download best format available but no better than 480p $ youtube-dl -f 'bestvideo[height<=480]+bestaudio/best[height<=480]' # Download best video only format but no bigger than 50 MB $ youtube-dl -f 'best[filesize<50M]' # Download best format available via direct link over HTTP/HTTPS protocol $ youtube-dl -f '(bestvideo+bestaudio/best)[protocol^=http]' # Download the best video format and the best audio format without merging them $ youtube-dl -f 'bestvideo,bestaudio' -o '%(title)s.f%(format_id)s.%(ext)s'
Note that in the last example, an output template is recommended as bestvideo and bestaudio may have the same file name.
3:剪接 mp3
我們想要取影片中的一小段時… 可以利用ffmpeg下個指令就好了
ffmpeg -ss 00:20:48.500 -t 00:01:00 -i INPUT.mp4 OUTPUT.mp4
- -ss 是指影片的第幾分幾秒開始剪
- -t 是指要剪多少時間, 如果不使用就會直接到檔案最後。
- -acodec copy -vcodec copy 這個參數不是預設值,沒有下的話會變成預設的編碼,會很慢。
較佳解法:
ffmpeg -ss 開始時間 -t 長度 -i 原來檔案.mp4 -acodec copy -vcodec copy 輸出檔案.mp4
服用了參數 -acodec copy -vcodec copy ,剪接即使是 2~3小時的mp3,幾乎都是一秒內搞定。如果來源檔是mp3就不用加上面這個參數,反正一下子就處理完了,是為了要處理超長的影片才需要使用。
附註:-acode copy 的參數,要「夾在」第二個檔案的前面,沒辦法在最前面加,或加在最後面,這一點有點怪怪的!
範例1:直接全部內容轉mp3
ffmpeg -i video.mp4 audio.mp3
範例2:mp3第10秒起,剪下6秒
ffmpeg -ss 10 -i input.mp3 -t 6 output.mp3
範例3:mp3去掉前30秒
ffmpeg -ss 30 -i inputfile.mp3 outputfile.mp3
-ss 是指影片的第幾分幾秒開始剪
-t 是指要剪多少時間
要去掉尾部的秒數,直接使用 -t 參數。
範例4:mp3 增加縮圖
詳細用法參考:
https://www.ffmpeg.org/ffmpeg.html#toc-Main-options
ffmpeg -i in.mp3 -i in.jpg -map 1 -map 0 -c copy -disposition:0 attached_pic out.mp3
如果想要取得youtube 影片的縮圖,可以google 關鍵字 download youtube thumbnail ,有很多類似服務的網站,例如:
https://youtube-thumbnail-grabber.com/
例如我有一部影片檔案大小 4.7GB 要分割成 2個小檔案,所以分別執行下面二行指令即可完成任務:
- 前1小時,切成一個獨立檔案: ffmpeg -t 01:00:00 -i 蟻人1.Ant.Man.\(2015\).mp4 -acodec copy -vcodec copy output1.mp4
-
第2個小時到最後,切成一個獨立檔案:
ffmpeg -ss 01:00:00 -i 蟻人1.Ant.Man.\(2015\).mp4 -acodec copy -vcodec copy output2.mp4
剪輯多音軌範例:
# fmpeg -i input.mkv ffmpeg version ... Copyright (c) 2000-2012 the FFmpeg developers ... Input #0, matroska,webm, from 'input.mkv': Duration: 01:39:44.02, start: 0.000000, bitrate: 5793 kb/s Stream #0:0(eng): Video: h264 (High), yuv420p, 1920x800, 23.98 fps, 23.98 tbr, 1k tbn, 47.95 tbc (default) Stream #0:1(ger): Audio: dts (DTS), 48000 Hz, 5.1(side), s16, 1536 kb/s (default) Stream #0:2(eng): Audio: dts (DTS), 48000 Hz, 5.1(side), s16, 1536 kb/s Stream #0:3(ger): Subtitle: text (default) At least one output file must be specified
Example 1
Now, let’s say we want to:
- copy video stream
- encode german audio stream to mp3 (128kbps) and aac (96kbps) (creating 2 audio streams in the output)
- drop english audio stream
- copy subtitle stream
This can be done using the following FFmpeg command line:
ffmpeg -i input.mkv \ -map 0:0 -map 0:1 -map 0:1 -map 0:3 \ -c:v copy \ -c:a:0 libmp3lame -b:a:0 128k \ -c:a:1 libfaac -b:a:1 96k \ -c:s copy \ output.mkv
Note there is no “-map 0:2” and that “-map 0:1” has been specified twice.
Using “-map 0:0 -map 0:1 -map 0:1 -map 0:3” we told FFmpeg to select/map specified input streams to output in that order.
So, our output will now have the following streams:
Output #0, matroska, to 'output.mkv': Stream #0:0(eng): Video ... Stream #0:1(ger): Audio ... Stream #0:2(ger): Audio ... Stream #0:3(ger): Subtitle ...
After we selected which streams we would like in our output, using “-map” option, we specified codecs for each stream in our output.
Video and subtitle stream have just been copied and german audio stream has been encoded to 2 new audio streams, mp3 and aac.
We used “-c:a:0” to specify codec for the output’s first AUDIO stream and “-c:a:1” to specify codec for the output’s second AUDIO stream.
Note that “a:0” refers to the output’s first AUDIO stream (#0:1 in our case), “a:1” refers to the output’s 2nd AUDIO stream (which is also mapped to the input stream #0:1), etc.
The result will be:
Output #0, matroska, to 'output.mkv': Stream #0:0(eng): Video ... Stream #0:1(ger): Audio ... Stream #0:2(ger): Audio ... Stream #0:3(ger): Subtitle ... Stream mapping: Stream #0:0 -> #0:0 (copy) Stream #0:1 -> #0:1 (dca -> libmp3lame) Stream #0:2 -> #0:2 (dca -> libfaac) Stream #0:3 -> #0:3 (copy)
Example 2
Let’s say that we want to reorder input streams backwards, so that we have output like this:
Stream #0:0(ger): Subtitle: text (default) Stream #0:1(eng): Audio: dts (DTS), 48000 Hz, 5.1(side), s16, 1536 kb/s Stream #0:2(ger): Audio: dts (DTS), 48000 Hz, 5.1(side), s16, 1536 kb/s (default) Stream #0:3(eng): Video: h264 (High), yuv420p, 1920x800, 23.98 fps, 23.98 tbr, 1k tbn, 47.95 tbc (default)
This can simply be done using the following command line:
ffmpeg -i input.mkv -map 0:3 -map 0:2 -map 0:1 -map 0:0 -c copy output.mkv
Note that we specified all the input streams, but in the reverse order, which causes that order to be respected in the output.
The option “-c copy” tells FFmpeg to use “copy” on all streams.
Example 3
If we want to extract only audio streams, from the same input file, then we can do it like this:
ffmpeg -i input.mkv -map 0:1 -map 0:2 -c copy output.mkv
Example 4
If we want to re-encode just the video streams, but copy all the other streams (like audio, subtitles, attachments, etc), we might use something like this:
ffmpeg -i input.mkv -map 0 -c copy -c:v mpeg2video output.mkv
It will tell ffmpeg to:
- read the input file ‘input.mkv’
- select all the input streams (first input = 0) to be processed (using “-map 0”)
- mark all the streams to be just copied to the output (using “-c copy”)
- mark just the video streams to be re-encoded (using “-c:v mpeg2video”)
- write the output file ‘output.mkv’
Example 5
You can use the “-map” command in creating multiple output files, ex:
ffmpeg -i input.mkv -map 0:1 -map 0:2 audios_only.mkv -map 0:0 video_only.mkv
The default is to map the “highest quality video” and “highest quality audio” to each output file (basically reuses it for each output), see also Creating multiple outputs.
Example 6
You can use the named output of a filtergraph as a mapping parameter, ex:
ffmpeg -i INPUT -filter_complex "[0] scale=100x100[smaller_sized]" -map "[smaller_sized]" out.mp4
which (in our example) is the same as specifying the stream more precisely, and equivalent to this
ffmpeg -i INPUT -filter_complex "[0:0] scale=100x100[smaller_sized]" -map "[smaller_sized]" out.mp4
Example 7
There are stream selection shortcuts you can also use like “0:v”
ffmpeg -i input -map 0:v -map 0:a output.mkv # chooses video and audio from input 0
See stream specifiers for details.
Example 8
MPEG stream selection:
The tricky part with selecting from MPEG TS is it may contain multiple streams/channels, and if you are receiving “live data” just specifying an index might not work because it can change from run to run, so
ffmpeg -i INPUT -map 0:6 OUTPUT # might not work the same every run, DO NOT USE THIS WAY!
Assuming your file is MPEG, you can run “ffmpeg -i INPUT” (not specify an output) to see what program id’s and stream id’s it contains, like this example (probesize and analyzeduration specified to help “make sure” it picks up all the streams in it, may not be always needed)
$ ffmpeg -probesize 50M -analyzeduration 50M -i INPUT ... Input #0, mpegts, from 'INPUT': Duration: N/A, start: 22159.226833, bitrate: N/A Program 1344 Metadata: service_name : 7 Digital service_provider: Seven Network Stream #0:0[0x401]: Video: mpeg2video (Main) ([2][0][0][0] / 0x0002), yuv420p(tv), 720x576 [SAR 64:45 DAR 16:9], max. 14950 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc Stream #0:1[0x402](eng): Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 256 kb/s Program 1346 Metadata: service_name : 7TWO service_provider: Seven Network Stream #0:3[0x406]: Unknown: none ([5][0][0][0] / 0x0005) Stream #0:6[0x421]: Video: mpeg2video (Main) ([2][0][0][0] / 0x0002), yuv420p(tv), 720x576 [SAR 64:45 DAR 16:9], max. 14950 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc Stream #0:7[0x422](eng): Audio: mp2 ([3][0][0][0] / 0x0003), 48000 Hz, stereo, s16p, 192 kb/s Stream #0:8[0x424](eng): Subtitle: dvb_teletext ([6][0][0][0] / 0x0006), 492x250 Stream #0:4[0x499]: Unknown: none ([11][0][0][0] / 0x000B)
you could specify desired streams by program id:
ffmpeg -i INPUT -map 0:p:1344 OUTPUT # pulls in both inputs from program 1344, channel "7 Digital" in this case
or specify a child stream:
ffmpeg -i INPUT -map i:0x401 OUTPUT # pulls in the single input stream with PID (MPEG Packet ID [stream identifier]) 0x401 from wherever it is found, in this case its a video stream in "7 Digital"
or similar, see other specifier examples. Note if you have “unknown” streams in there you may need to add the -ignore_unknown flag as well.
Also note that if your input stream contains multiple program id’s, you can record simultaneously from various of them, using the same FFmpeg instance and the map commands described here.
Example 9
Include “all” inputs to the output. The default behavior is to copy only one audio and one video channel. If you want to copy ‘all’ channels, use “-map”
# re encodes all video and audio channels from input one ffmpeg -i input -map 0 output.mp4 # copies all video and audio channels from input one to output, not just one video ffmpeg -i input -map 0 -c copy output.mp4
範例9 號滿實用的,因為使用參數:-acodec copy -vcodec copy 只會輸出第一個音軌, 如果使用 -map 0 -c copy 則可以輸出所有音軌出來。
要知道多媒體檔案的資訊,可以「不放輸出檔案的參數」,即可取得所有 stream 的資訊。
轉檔,透過 bitrate 縮小檔案:
The typical example would be something like this:
ffmpeg -i input -c:v libx264 -b:v 2M -maxrate 2M -bufsize 1M output.mp4
由於youtube 會有很多個編碼格式,youtube-dl 可能猜測的不是最佳的,或是最佳的格式並不適合你的播放器,你可以先用參數 –list-formats (或使用 -F)去取得最佳格式:
--list-formats
針對 resolution note 選取偏愛的 format code 再使用參數 –format (或使用 -f)去取得影片:
--format
增加音軌到影片檔案:
FFMPEG add additional audio track in video (mix 2 audio)
ffmpeg -i video.mp4 -i audio.wav -c:v copy -c:a copy -strict experimental output.mp4
Here, we assume that the video file does not contain any audio stream yet, and that you want to have the same output format (here, MP4) as the input format.
The above command transcodes the audio, since MP4s cannot carry PCM audio streams. You can use any other desired audio codec if you want. See the AAC Encoding Guide for more info.
If your audio or video stream is longer, you can add the -shortest
option so that ffmpeg will stop encoding once one file ends.
Copying the audio without re-encoding
If your output container can handle (almost) any codec – like MKV – then you can simply copy both audio and video streams:
ffmpeg -i video.mp4 -i audio.wav -c copy output.mkv
Replacing audio stream
If your input video already contains audio, and you want to replace it, you need to tell ffmpeg which audio stream to take:
ffmpeg -i video.mp4 -i audio.wav \
-c:v copy -c:a aac -strict experimental \
-map 0:v:0 -map 1:a:0 output.mp4
The map
option makes ffmpeg only use the first video stream from the first input and the first audio stream from the second input for the output file.
附註 youtube-dl 完整參數:
youtube-dl is a command-line program to download videos from YouTube.com and a few more sites. It requires the Python interpreter, version 2.6, 2.7, or 3.2+, and it is not platform specific. It should work on your Unix box, on Windows or on Mac OS X. It is released to the public domain, which means you can modify it, redistribute it or use it however you like.
youtube-dl [OPTIONS] URL [URL...]
OPTIONS
-h, --help Print this help text and exit
--version Print program version and exit
-U, --update Update this program to latest version. Make
sure that you have sufficient permissions
(run with sudo if needed)
-i, --ignore-errors Continue on download errors, for example to
skip unavailable videos in a playlist
--abort-on-error Abort downloading of further videos (in the
playlist or the command line) if an error
occurs
--dump-user-agent Display the current browser identification
--list-extractors List all supported extractors
--extractor-descriptions Output descriptions of all supported
extractors
--force-generic-extractor Force extraction to use the generic
extractor
--default-search PREFIX Use this prefix for unqualified URLs. For
example "gvsearch2:" downloads two videos
from google videos for youtube-dl "large
apple". Use the value "auto" to let
youtube-dl guess ("auto_warning" to emit a
warning when guessing). "error" just throws
an error. The default value "fixup_error"
repairs broken URLs, but emits an error if
this is not possible instead of searching.
--ignore-config Do not read configuration files. When given
in the global configuration file
/etc/youtube-dl.conf: Do not read the user
configuration in ~/.config/youtube-
dl/config (%APPDATA%/youtube-dl/config.txt
on Windows)
--config-location PATH Location of the configuration file; either
the path to the config or its containing
directory.
--flat-playlist Do not extract the videos of a playlist,
only list them.
--mark-watched Mark videos watched (YouTube only)
--no-mark-watched Do not mark videos watched (YouTube only)
--no-color Do not emit color codes in output
Network Options:
--proxy URL Use the specified HTTP/HTTPS/SOCKS proxy.
To enable experimental SOCKS proxy, specify
a proper scheme. For example
socks5://127.0.0.1:1080/. Pass in an empty
string (--proxy "") for direct connection
--socket-timeout SECONDS Time to wait before giving up, in seconds
--source-address IP Client-side IP address to bind to
-4, --force-ipv4 Make all connections via IPv4
-6, --force-ipv6 Make all connections via IPv6
Geo Restriction:
--geo-verification-proxy URL Use this proxy to verify the IP address for
some geo-restricted sites. The default
proxy specified by --proxy (or none, if the
options is not present) is used for the
actual downloading.
--geo-bypass Bypass geographic restriction via faking
X-Forwarded-For HTTP header (experimental)
--no-geo-bypass Do not bypass geographic restriction via
faking X-Forwarded-For HTTP header
(experimental)
--geo-bypass-country CODE Force bypass geographic restriction with
explicitly provided two-letter ISO 3166-2
country code (experimental)
Video Selection:
--playlist-start NUMBER Playlist video to start at (default is 1)
--playlist-end NUMBER Playlist video to end at (default is last)
--playlist-items ITEM_SPEC Playlist video items to download. Specify
indices of the videos in the playlist
separated by commas like: "--playlist-items
1,2,5,8" if you want to download videos
indexed 1, 2, 5, 8 in the playlist. You can
specify range: "--playlist-items
1-3,7,10-13", it will download the videos
at index 1, 2, 3, 7, 10, 11, 12 and 13.
--match-title REGEX Download only matching titles (regex or
caseless sub-string)
--reject-title REGEX Skip download for matching titles (regex or
caseless sub-string)
--max-downloads NUMBER Abort after downloading NUMBER files
--min-filesize SIZE Do not download any videos smaller than
SIZE (e.g. 50k or 44.6m)
--max-filesize SIZE Do not download any videos larger than SIZE
(e.g. 50k or 44.6m)
--date DATE Download only videos uploaded in this date
--datebefore DATE Download only videos uploaded on or before
this date (i.e. inclusive)
--dateafter DATE Download only videos uploaded on or after
this date (i.e. inclusive)
--min-views COUNT Do not download any videos with less than
COUNT views
--max-views COUNT Do not download any videos with more than
COUNT views
--match-filter FILTER Generic video filter. Specify any key (see
the "OUTPUT TEMPLATE" for a list of
available keys) to match if the key is
present, !key to check if the key is not
present, key > NUMBER (like "comment_count
> 12", also works with >=, <, <=, !=, =) to
compare against a number, key = 'LITERAL'
(like "uploader = 'Mike Smith'", also works
with !=) to match against a string literal
and & to require multiple matches. Values
which are not known are excluded unless you
put a question mark (?) after the operator.
For example, to only match videos that have
been liked more than 100 times and disliked
less than 50 times (or the dislike
functionality is not available at the given
service), but who also have a description,
use --match-filter "like_count > 100 &
dislike_count <? 50 & description" .
--no-playlist Download only the video, if the URL refers
to a video and a playlist.
--yes-playlist Download the playlist, if the URL refers to
a video and a playlist.
--age-limit YEARS Download only videos suitable for the given
age
--download-archive FILE Download only videos not listed in the
archive file. Record the IDs of all
downloaded videos in it.
--include-ads Download advertisements as well
(experimental)
Download Options:
-r, --limit-rate RATE Maximum download rate in bytes per second
(e.g. 50K or 4.2M)
-R, --retries RETRIES Number of retries (default is 10), or
"infinite".
--fragment-retries RETRIES Number of retries for a fragment (default
is 10), or "infinite" (DASH, hlsnative and
ISM)
--skip-unavailable-fragments Skip unavailable fragments (DASH, hlsnative
and ISM)
--abort-on-unavailable-fragment Abort downloading when some fragment is not
available
--keep-fragments Keep downloaded fragments on disk after
downloading is finished; fragments are
erased by default
--buffer-size SIZE Size of download buffer (e.g. 1024 or 16K)
(default is 1024)
--no-resize-buffer Do not automatically adjust the buffer
size. By default, the buffer size is
automatically resized from an initial value
of SIZE.
--playlist-reverse Download playlist videos in reverse order
--playlist-random Download playlist videos in random order
--xattr-set-filesize Set file xattribute ytdl.filesize with
expected file size (experimental)
--hls-prefer-native Use the native HLS downloader instead of
ffmpeg
--hls-prefer-ffmpeg Use ffmpeg instead of the native HLS
downloader
--hls-use-mpegts Use the mpegts container for HLS videos,
allowing to play the video while
downloading (some players may not be able
to play it)
--external-downloader COMMAND Use the specified external downloader.
Currently supports
aria2c,avconv,axel,curl,ffmpeg,httpie,wget
--external-downloader-args ARGS Give these arguments to the external
downloader
Filesystem Options:
-a, --batch-file FILE File containing URLs to download ('-' for
stdin)
--id Use only video ID in file name
-o, --output TEMPLATE Output filename template, see the "OUTPUT
TEMPLATE" for all the info
--autonumber-start NUMBER Specify the start value for %(autonumber)s
(default is 1)
--restrict-filenames Restrict filenames to only ASCII
characters, and avoid "&" and spaces in
filenames
-w, --no-overwrites Do not overwrite files
-c, --continue Force resume of partially downloaded files.
By default, youtube-dl will resume
downloads if possible.
--no-continue Do not resume partially downloaded files
(restart from beginning)
--no-part Do not use .part files - write directly
into output file
--no-mtime Do not use the Last-modified header to set
the file modification time
--write-description Write video description to a .description
file
--write-info-json Write video metadata to a .info.json file
--write-annotations Write video annotations to a
.annotations.xml file
--load-info-json FILE JSON file containing the video information
(created with the "--write-info-json"
option)
--cookies FILE File to read cookies from and dump cookie
jar in
--cache-dir DIR Location in the filesystem where youtube-dl
can store some downloaded information
permanently. By default
$XDG_CACHE_HOME/youtube-dl or
~/.cache/youtube-dl . At the moment, only
YouTube player files (for videos with
obfuscated signatures) are cached, but that
may change.
--no-cache-dir Disable filesystem caching
--rm-cache-dir Delete all filesystem cache files
Thumbnail images:
--write-thumbnail Write thumbnail image to disk
--write-all-thumbnails Write all thumbnail image formats to disk
--list-thumbnails Simulate and list all available thumbnail
formats
Verbosity / Simulation Options:
-q, --quiet Activate quiet mode
--no-warnings Ignore warnings
-s, --simulate Do not download the video and do not write
anything to disk
--skip-download Do not download the video
-g, --get-url Simulate, quiet but print URL
-e, --get-title Simulate, quiet but print title
--get-id Simulate, quiet but print id
--get-thumbnail Simulate, quiet but print thumbnail URL
--get-description Simulate, quiet but print video description
--get-duration Simulate, quiet but print video length
--get-filename Simulate, quiet but print output filename
--get-format Simulate, quiet but print output format
-j, --dump-json Simulate, quiet but print JSON information.
See the "OUTPUT TEMPLATE" for a description
of available keys.
-J, --dump-single-json Simulate, quiet but print JSON information
for each command-line argument. If the URL
refers to a playlist, dump the whole
playlist information in a single line.
--print-json Be quiet and print the video information as
JSON (video is still being downloaded).
--newline Output progress bar as new lines
--no-progress Do not print progress bar
--console-title Display progress in console titlebar
-v, --verbose Print various debugging information
--dump-pages Print downloaded pages encoded using base64
to debug problems (very verbose)
--write-pages Write downloaded intermediary pages to
files in the current directory to debug
problems
--print-traffic Display sent and read HTTP traffic
-C, --call-home Contact the youtube-dl server for debugging
--no-call-home Do NOT contact the youtube-dl server for
debugging
Workarounds:
--encoding ENCODING Force the specified encoding (experimental)
--no-check-certificate Suppress HTTPS certificate validation
--prefer-insecure Use an unencrypted connection to retrieve
information about the video. (Currently
supported only for YouTube)
--user-agent UA Specify a custom user agent
--referer URL Specify a custom referer, use if the video
access is restricted to one domain
--add-header FIELD:VALUE Specify a custom HTTP header and its value,
separated by a colon ':'. You can use this
option multiple times
--bidi-workaround Work around terminals that lack
bidirectional text support. Requires bidiv
or fribidi executable in PATH
--sleep-interval SECONDS Number of seconds to sleep before each
download when used alone or a lower bound
of a range for randomized sleep before each
download (minimum possible number of
seconds to sleep) when used along with
--max-sleep-interval.
--max-sleep-interval SECONDS Upper bound of a range for randomized sleep
before each download (maximum possible
number of seconds to sleep). Must only be
used along with --min-sleep-interval.
Video Format Options:
-f, --format FORMAT Video format code, see the "FORMAT
SELECTION" for all the info
--all-formats Download all available video formats
--prefer-free-formats Prefer free video formats unless a specific
one is requested
-F, --list-formats List all available formats of requested
videos
--youtube-skip-dash-manifest Do not download the DASH manifests and
related data on YouTube videos
--merge-output-format FORMAT If a merge is required (e.g.
bestvideo+bestaudio), output to given
container format. One of mkv, mp4, ogg,
webm, flv. Ignored if no merge is required
Subtitle Options:
--write-sub Write subtitle file
--write-auto-sub Write automatically generated subtitle file
(YouTube only)
--all-subs Download all the available subtitles of the
video
--list-subs List all available subtitles for the video
--sub-format FORMAT Subtitle format, accepts formats
preference, for example: "srt" or
"ass/srt/best"
--sub-lang LANGS Languages of the subtitles to download
(optional) separated by commas, use --list-
subs for available language tags
Authentication Options:
-u, --username USERNAME Login with this account ID
-p, --password PASSWORD Account password. If this option is left
out, youtube-dl will ask interactively.
-2, --twofactor TWOFACTOR Two-factor authentication code
-n, --netrc Use .netrc authentication data
--video-password PASSWORD Video password (vimeo, smotri, youku)
Adobe Pass Options:
--ap-mso MSO Adobe Pass multiple-system operator (TV
provider) identifier, use --ap-list-mso for
a list of available MSOs
--ap-username USERNAME Multiple-system operator account login
--ap-password PASSWORD Multiple-system operator account password.
If this option is left out, youtube-dl will
ask interactively.
--ap-list-mso List all supported multiple-system
operators
Post-processing Options:
-x, --extract-audio Convert video files to audio-only files
(requires ffmpeg or avconv and ffprobe or
avprobe)
--audio-format FORMAT Specify audio format: "best", "aac",
"flac", "mp3", "m4a", "opus", "vorbis", or
"wav"; "best" by default; No effect without
-x
--audio-quality QUALITY Specify ffmpeg/avconv audio quality, insert
a value between 0 (better) and 9 (worse)
for VBR or a specific bitrate like 128K
(default 5)
--recode-video FORMAT Encode the video to another format if
necessary (currently supported:
mp4|flv|ogg|webm|mkv|avi)
--postprocessor-args ARGS Give these arguments to the postprocessor
-k, --keep-video Keep the video file on disk after the post-
processing; the video is erased by default
--no-post-overwrites Do not overwrite post-processed files; the
post-processed files are overwritten by
default
--embed-subs Embed subtitles in the video (only for mp4,
webm and mkv videos)
--embed-thumbnail Embed thumbnail in the audio as cover art
--add-metadata Write metadata to the video file
--metadata-from-title FORMAT Parse additional metadata like song title /
artist from the video title. The format
syntax is the same as --output. Regular
expression with named capture groups may
also be used. The parsed parameters replace
existing values. Example: --metadata-from-
title "%(artist)s - %(title)s" matches a
title like "Coldplay - Paradise". Example
(regex): --metadata-from-title
"(?P<artist>.+?) - (?P<title>.+)"
--xattrs Write metadata to the video file's xattrs
(using dublin core and xdg standards)
--fixup POLICY Automatically correct known faults of the
file. One of never (do nothing), warn (only
emit a warning), detect_or_warn (the
default; fix file if we can, warn
otherwise)
--prefer-avconv Prefer avconv over ffmpeg for running the
postprocessors (default)
--prefer-ffmpeg Prefer ffmpeg over avconv for running the
postprocessors
--ffmpeg-location PATH Location of the ffmpeg/avconv binary;
either the path to the binary or its
containing directory.
--exec CMD Execute a command on the file after
downloading, similar to find's -exec
syntax. Example: --exec 'adb push {}
/sdcard/Music/ && rm {}'
--convert-subs FORMAT Convert the subtitles to other format
(currently supported: srt|ass|vtt)
如果遇到下面的錯誤訊息:
WARNING: Unable to download webpage: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)> [youtube] aa2AhDaK_iY: Downloading API JSON ERROR: Unable to download API page: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)> (caused by URLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)')))
解法:增加參數 –no-check-certificate
dd the no-check-certificate
parameter to the command:
youtube-dl --no-check-certificate
資料來源:
https://stackoverflow.com/questions/60158087/youtubedl-certificate-verify-failed
4: 合併mp3
比較簡單的作法是建立一個文字檔,內容如下:
file '/path/to/first.mp3'
file '/path/to/second.mp3'
再服用 ffmpeg 指令,就可以合併成單一 mp3 檔案:
ffmpeg -f concat -i list.txt -c copy out.mp3
附註:文字檔不太能使用中文及emoji,建議改用英文或數字,就會沒問題,錯誤訊息如下:
[concat @ 0x7ffae7013a00] Unsafe file name 'A-Lin -《千尋》(電視劇《千古玦塵》插曲)🎵『無損高音質|CC歌詞字幕』-VE3p6-IGKG4.mp3'
list.txt: Operation not permitted
如果想要重新編碼(re-encoding)服用下面指令:
ffmpeg -i first.mp3 -i second.mp3 -filter_complex [0:a][1:a]concat=n=2:v=0:a=1 out.mp3
另一個範例,FFmpeg combine mp3 files to one mp3 file with delays
ffmpeg -i aaa.mp3 -i aab.mp3 -filter_complex "[0]adelay=10000|10000[a];[1]adelay=10000|10000[b];[a][b]amix=inputs=2" out.mp3
aaa.mp3 is input 0
aab.mp3 is input 1
[0]adelay=10000|10000[a]
Means take input 0 and add a delay of 10000milliseconds on both channel and name the stream specifier ‘a’
[1]adelay=10000|10000[b]
Take input 1 and add a delay of 10000milliseconds on both channel and the stream specifier ‘b’
[a][b]amix=inputs=2
mix the stream specifier called ‘a’ and ‘b’.
Here is a video that can help you to understand ffmpeg filter graph. https://youtu.be/hElDsyuAQDA?t=341