1

Androidで映像をカメラから録画するだけのアプリをつくっています。
画面上にカメラからの映像をプレビューし、それを録画するだけのアプリです。
録画機能はまだ実装していませんがMediaRecorderの初期化とプレビュー画面の表示すらできません。なぜでしょうか?

kotlinとjetpack composeを使用していて、Android 12をtargetに開発しています。

エラーログ:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.simpledriverwatcher, PID: 26536
    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:558)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
     Caused by: android.hardware.camera2.CameraAccessException: CAMERA_DISABLED (1): validateClientPermissionsLocked:1227: Caller "com.example.simpledriverwatcher" (PID 10392, UID 26536) cannot open camera "0" from background (calling UID 10392 proc state 20)
        at android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:1179)
        at android.hardware.camera2.CameraManager.openCameraDeviceUserAsync(CameraManager.java:616)
        at android.hardware.camera2.CameraManager.openCameraForUid(CameraManager.java:866)
        at android.hardware.camera2.CameraManager.openCameraForUid(CameraManager.java:887)
        at android.hardware.camera2.CameraManager.openCamera(CameraManager.java:725)
        at com.example.simpledriverwatcher.MainActivityKt$CameraPreview$1.invoke(MainActivity.kt:101)
        at com.example.simpledriverwatcher.MainActivityKt$CameraPreview$1.invoke(MainActivity.kt:78)
        at androidx.compose.ui.viewinterop.ViewFactoryHolder.setFactory(AndroidView.android.kt:144)
        at androidx.compose.ui.viewinterop.AndroidView_androidKt$AndroidView$1.invoke(AndroidView.android.kt:90)
        at androidx.compose.ui.viewinterop.AndroidView_androidKt$AndroidView$1.invoke(AndroidView.android.kt:88)
        at androidx.compose.ui.viewinterop.AndroidView_androidKt$AndroidView$$inlined$ComposeNode$1.invoke(Composables.kt:212)
        at androidx.compose.runtime.ComposerImpl$createNode$2.invoke(Composer.kt:1362)
        at androidx.compose.runtime.ComposerImpl$createNode$2.invoke(Composer.kt:1360)
        at androidx.compose.runtime.ComposerImpl$recordInsert$2.invoke(Composer.kt:2763)
        at androidx.compose.runtime.ComposerImpl$recordInsert$2.invoke(Composer.kt:2760)
        at androidx.compose.runtime.CompositionImpl.applyChanges(Composition.kt:629)
        at androidx.compose.runtime.Recomposer.composeInitial$runtime_release(Recomposer.kt:733)
        at androidx.compose.runtime.CompositionImpl.setContent(Composition.kt:432)
        at androidx.compose.ui.platform.WrappedComposition$setContent$1.invoke(Wrapper.android.kt:144)
        at androidx.compose.ui.platform.WrappedComposition$setContent$1.invoke(Wrapper.android.kt:135)
        at androidx.compose.ui.platform.AndroidComposeView.setOnViewTreeOwnersAvailable(AndroidComposeView.android.kt:727)
        at androidx.compose.ui.platform.WrappedComposition.setContent(Wrapper.android.kt:135)
        at androidx.compose.ui.platform.WrappedComposition.onStateChanged(Wrapper.android.kt:187)
        at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:354)
        at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:196)
        at androidx.compose.ui.platform.WrappedComposition$setContent$1.invoke(Wrapper.android.kt:142)
        at androidx.compose.ui.platform.WrappedComposition$setContent$1.invoke(Wrapper.android.kt:135)
        at androidx.compose.ui.platform.AndroidComposeView.onAttachedToWindow(AndroidComposeView.android.kt:814)
        at android.view.View.dispatchAttachedToWindow(View.java:20753)
        at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3490)
        at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3497)
        at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3497)
        at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3497)
        at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3497)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2613)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2126)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8649)
E/AndroidRuntime:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1037)
        at android.view.Choreographer.doCallbacks(Choreographer.java:845)
        at android.view.Choreographer.doFrame(Choreographer.java:780)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1022)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7842)
            ... 3 more
     Caused by: android.os.ServiceSpecificException: validateClientPermissionsLocked:1227: Caller "com.example.simpledriverwatcher" (PID 10392, UID 26536) cannot open camera "0" from background (calling UID 10392 proc state 20) (code 6)
        at android.os.Parcel.createExceptionOrNull(Parcel.java:2439)
        at android.os.Parcel.createException(Parcel.java:2409)
        at android.os.Parcel.readException(Parcel.java:2392)
        at android.os.Parcel.readException(Parcel.java:2334)
        at android.hardware.ICameraService$Stub$Proxy.connectDevice(ICameraService.java:669)
        at android.hardware.camera2.CameraManager.openCameraDeviceUserAsync(CameraManager.java:596)
            ... 47 more
I/Process: Sending signal. PID: 26536 SIG: 9

コード1:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        var mr: MediaRecorder = MediaRecorder()
        mr.reset()
        setContent {
            SimpleDriverWatcherTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    Box(modifier = Modifier.fillMaxSize()) {
                        var rec_state = remember { mutableStateOf(false)}
                        CameraPreview(mr, rec_state)
                        Button(
                            enabled = true,
                            onClick = {
                                rec_state.value = !rec_state.value
                            },
                            modifier = Modifier
                                .padding(0.dp, 0.dp, 0.dp, 30.dp)
                                .size(80.dp)
                                .align(Alignment.BottomCenter),
                            shape = CircleShape
                        ) {
                            Icon(Icons.Default.FiberManualRecord, null, modifier = Modifier.size(50.dp), tint = Color.Red)
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

@Composable
fun CameraPreview(mediaRecorder: MediaRecorder, stat: State<Boolean>) {
    AndroidView(modifier = Modifier.fillMaxSize(), factory = { ctx ->
        android.view.SurfaceView(ctx).apply {
            var cam_m: CameraManager?
            var curr_cam_id: String = ""
            var sysservice = ctx.getSystemService(CAMERA_SERVICE)
            cam_m = sysservice as CameraManager
            var cam_ids = cam_m.cameraIdList
            for (i in cam_ids) {
                Log.d("Hello", "World")
                val cam_char = cam_m.getCameraCharacteristics(i)
                val lens_facing = cam_char.get(CameraCharacteristics.LENS_FACING)
                if (lens_facing == CameraMetadata.LENS_FACING_BACK) {
                    curr_cam_id = i
                    break
                }
            }
            if (curr_cam_id == "") {
                Log.d("Camera", "Camera does not exist")

            }

            when {
                context.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED -> {
                    cam_m!!.openCamera(curr_cam_id, MyCameraStatecallback(context, this, mediaRecorder), null)
                }
                else -> {
                    requestPermissions(ctx as Activity, arrayOf(Manifest.permission.CAMERA), 449)
                }
            }

        }
    })
}



class MyCameraStatecallback(val context: Context, val surfaceView: android.view.SurfaceView, val mr: MediaRecorder) : CameraDevice.StateCallback() {
    override fun onOpened(camera: CameraDevice) {
        InitMediaRecorder(context, mr)
        mr.prepare()
        val opc = OutputConfiguration(surfaceView.holder.surface)
        val opc2 = OutputConfiguration(mr.surface)
        val lopc = listOf(opc, opc2)
        val cam_cap_thread = HandlerThread("CameraCaptureThread")
        cam_cap_thread.start()
        camera.createCaptureSession(
            SessionConfiguration(
                SessionConfiguration.SESSION_REGULAR,
                lopc,
                context.mainExecutor,
                myCaptureStatecallback(context, surfaceView, mediaRecorder = mr)
            )
        )

    }

    override fun onDisconnected(camera: CameraDevice) {
        Toast.makeText(context, "Camera Disconnected", Toast.LENGTH_LONG)
    }

    override fun onError(camera: CameraDevice, error: Int) {
        Log.e("Error", "CameraDevice.StateCallbackError")
        Toast.makeText(context, "camera error", Toast.LENGTH_LONG)
    }
}


class myCaptureStatecallback(val context: Context, val previewSurfaceView: SurfaceView, val mediaRecorder: MediaRecorder) : CameraCaptureSession.StateCallback() {
    override fun onReady(session: CameraCaptureSession) {
        var camdev = session.device as CameraDevice
        var cap_req_builder = camdev.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
        cap_req_builder.addTarget(previewSurfaceView.holder.surface)
        cap_req_builder.addTarget(mediaRecorder.surface)


        //cap_req_builder.addTarget(record_surface)
        session.setRepeatingRequest(
            cap_req_builder.build(),
            null,
            null
        )
    }

    override fun onConfigured(session: CameraCaptureSession) {

    }

    override fun onConfigureFailed(session: CameraCaptureSession) {
        session.close()
    }
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    SimpleDriverWatcherTheme {
            Button(enabled = true, onClick = {}, modifier = Modifier.size(100.dp), shape= CircleShape) {
                Text("Button")
            }
          //  CameraPreview()
    }
}

コード2:

fun InitMediaRecorder(context: Context, mr: MediaRecorder) : MediaRecorder {
    var res : String?
    var num : Int = 0
    var uri =MediaStore.Video.Media.EXTERNAL_CONTENT_URI
    var values = ContentValues()
    val resolver = context.contentResolver
    val p = Pattern.compile("""^SimpleDriverWatch\d+.mp4$""")
    val projection = arrayOf(MediaStore.Video.Media.DISPLAY_NAME)
    val sortorder = "${MediaStore.Video.Media.DISPLAY_NAME} DESC"
    val query = context.contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
    projection,
    null,
    null,
    sortorder)

    query?.use {
        val display_name_column = it.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME)
        while (it.moveToNext()) {
            var dn = it.getString(display_name_column)
            var m = p.matcher(dn)
            if (m.matches()) {
                var file_num = m.group(1).toInt()
                if (file_num > num) {
                    num = file_num
                }
            }
        }
    }

    num++
    values.put(MediaStore.Video.Media.DISPLAY_NAME, "DriverWatcherVideo" + num.toString() + ".mp4")
    values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
    val output_url = resolver.insert(uri, values)
    val ofd = resolver.openFileDescriptor(output_url!!, "w")
    mr.reset()
    mr.setVideoSource(MediaRecorder.VideoSource.CAMERA)
    mr.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
    mr.setVideoEncoder(MediaRecorder.VideoEncoder.H264)
    mr.setVideoSize(720, 720)
    mr.setOutputFile(ofd!!.fileDescriptor)
    return@InitMediaRecorder mr
}

1 件の回答 1

1
Caused by: android.hardware.camera2.CameraAccessException: CAMERA_DISABLED (1): validateClientPermissionsLocked:1227:~~~

より、アプリにカメラパーミッションが与えられていないのではないでしょうか

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。