やりたいこと

Androidエミュレータのカメラは、標準では仮想シーンやソフトウェアで生成した映像を映す。
QRコードの読み取りなどを手元で試すには、PCに接続したWebカメラの映像をエミュレータのカメラに流したい。

emulatorコマンドの-camera-back/-camera-frontオプションにwebcam<N>を指定すると、エミュレータのカメラをPCのWebカメラに置き換えられる。

参考: 【Android】コマンドラインでエミュレータを立ち上げる

PCのカメラを確認する

-webcam-listオプションで、エミュレータから使えるWebカメラの一覧を表示する。

$ ~/Library/Android/sdk/emulator/emulator -webcam-list
List of web cameras connected to the computer:
 Camera '[カメラ名]' can be specified by label as 'webcam0' or by id as '[ID]' and will use pixel format 'NV12'
 Camera 'HD Webcam eMeet C960' can be specified by label as 'webcam1' or by id as '0x3112300328f006d' and will use pixel format 'NV12'

webcam0、webcam1がエミュレータのオプションに渡す名前である。
iPhoneの連係カメラなどもWebカメラとして一覧に表示される。使いたいカメラの番号を確認しておく。

Webカメラを指定して起動する

-camera-backにWebカメラの名前を指定して起動する。
以下の例ではwebcam1(HD Webcam eMeet C960)を使う。

$ ~/Library/Android/sdk/emulator/emulator -avd [AVD名] -port 5556 -camera-back webcam1
  • -camera-backは背面カメラ、-camera-frontは前面カメラを置き換える
  • AVDのカメラ設定より-camera-back/-camera-frontの指定が優先される
  • -portはシリアル(emulator-5556)を固定したい場合に指定する。省略時は空いているポートが自動で割り当てられる
  • カメラのオプションは起動時にのみ指定できる。起動済みのエミュレータはオプション付きで起動し直す

-camera-back/-camera-frontにはwebcam<N>以外に以下のモードも指定できる。

$ ~/Library/Android/sdk/emulator/emulator -help-camera-back

  Use -camera-back <mode> to control emulation of a camera facing back.
  Valid values for <mode> are:

     emulated             -> camera will be emulated using software ('fake') camera emulation
     webcam<N>            -> camera will be emulated using a webcamera connected to the host
     environment          -> If the feature is enabled, camera will render a virtual scene that's defined in environment.ini file of the AVD
     imagefile:<filename> -> Camera will render an image file.
     videofile:<filename> -> Camera will render a video file.
     image360:<filename>  -> Camera will render a panoramic image file.
     none                 -> camera emulation will be disabled

参考: コマンドラインからエミュレータを起動する | Android Studio | Android Developers

アプリで確認する

エミュレータで標準のカメラアプリや、開発中のアプリのスキャン画面を開く。
Webカメラの映像がプレビューに映れば成功。

macOSのカメラ許可

macOSでは、Webカメラの映像を初めて取得する際に、エミュレータを起動したターミナルアプリ(iTerm2など)に対してカメラへのアクセス許可が求められる。
ダイアログはエミュレータの起動時ではなく、Android側でカメラアプリを開いたタイミングで表示される。

許可されていない場合、カメラアプリのプレビューは真っ暗なままになる。
adb logcatには以下のエラーが繰り返し出力される。

E camera.provider.ranchu: qemuRunQuery:109 failure: failed to exec 'frame dim=1280x960 ...' query with Unable to obtain video frame from the camera

ダイアログで一度拒否すると、ダイアログは再表示されない。
上記のエラーが出る場合は「システム設定 > プライバシーとセキュリティ > カメラ」でターミナルアプリが許可されているかを確認する。