LoginSignup
20
12

More than 3 years have passed since last update.

MoviePyを使ったらいろいろつまづいたのでメモ

Last updated at Posted at 2020-03-07

動画編集をやりたく,moviepyを使ってみようと思ったがいろいろつまづいたのでメモ.

環境

mac Mojave
python 3.6.8

結論

「動画ファイルをInputとしてテキストや画像を追加し,Outputとしても動画ファイルを書き出す,」というユースケースなら以下が楽です.

pip install moviepy==1.0.0

## ※macのQuickTimePlayerでしか動作確認していないため,もしかしたらこっちじゃないと動かないかも
## moviepyのversion1.0.0を少しいじったもの
# pip install -U git+https://github.com/mynkit/moviepy.git@mynkit/dev

sample_moviepy.py

import moviepy.editor as mp


AUDIOPATH = 'hogehoge.mp4'
IMGPATH = 'hogehoge.png'


video = mp.VideoFileClip(AUDIOPATH)

img = (mp.ImageClip(IMGPATH)
          .set_start(1) # 動画の何秒地点から画像を表示させるか
          .set_duration(10) # 何秒間画像を表示させるか
          .resize(height=250) # 画像の高さ
          .margin(right=0, top=0, opacity=0) # 余白の大きさ設定(今回は余白なし)
          .set_pos(('right','bottom'))) # 今回は右下に画像を表示させる

final = mp.CompositeVideoClip([video, img])
# mynkit/devからpip installしてきた場合は `final.subclip(0,10).write_videofile('test.mp4')`のみで良い.
final.subclip(0,10).write_videofile(
    "test.mp4",
    codec='libx264', 
    audio_codec='aac', 
    temp_audiofile='temp-audio.m4a', 
    remove_temp=True
) # 0~10秒までをtest.mp4に出力

つまづきポイント

どうやらwrite_videofileがいろいろよろしくなさそう.

そもそもwrite_videofileが動かない

現時点(2020/03/07)のMoviePyの最新versionは1.1.0ですが,このままwrite_videofileを実行すると以下のエラーが出ます.

AttributeError: 'NoneType' object has no attribute 'stdout'

issue938をみると,versionを1.0.0に下げろとのこと.とりあえず言われた通りに下げる.

今度は出力ファイルから音声が出ない

入力ファイルには確かに音声あるし,jupyter上で

final.subclip(0,10).ipython_display(width=400)

したらちゃんと音声が存在する形でプレビューできた.だけど出力ファイルに音声がない..

これもissue876に記載があった.

moviepy/video/io/ffmpeg_writer.pyに記載されてる'-i', '-', '-an'の順番がおかしく,正しくは'-an', '-i', '-'とのこと.これはforkした自分のgithub上では対応しておいた.

ちなみにこの対応をしなくても,以下の対応だけすればQuickTimePlayerでは再生された.

macのQuickTimePlayerで再生できない

これで安心か,と思いきや,macのQuickTimePlayerで確認してみるとやはり音がでていない・・

issue51issue820でも言われている通り,QuickTimePlayerで再生するためにはwrite_videofileの引数に

    codec='libx264', 
    audio_codec='aac', 
    temp_audiofile='temp-audio.m4a', 
    remove_temp=True

が必要みたい.この状態で動画を書き出したところ,うまくいった.

20
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
12