Androidで映像をカメラから録画するだけのアプリをつくっています。
画面上にカメラからの映像をプレビューし、それを録画するだけのアプリです。
録画機能はまだ実装していませんがMediaRecorderの初期化とプレビュー画面の表示すらできません。
なぜでしょうか?
kotlinとjetpack composeを使用していて
いて、Android 12をtargetに開発しています。
コード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) {
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()
}
}
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
コード21:
class MainActivity : ComponentActivity() {
override fun InitMediaRecorderonCreate(contextsavedInstanceState: Context,Bundle?) {
super.onCreate(savedInstanceState)
var mr: MediaRecorder) := MediaRecorder()
mr.reset()
setContent {
var res : String? SimpleDriverWatcherTheme {
var num : Int = 0 // A surface container using the 'background' color from the theme
var uri =MediaStore Surface(color = MaterialTheme.Videocolors.Mediabackground) {
Box(modifier = Modifier.EXTERNAL_CONTENT_URIfillMaxSize()) {
var valuesrec_state = ContentValuesremember { mutableStateOf(false)}
val resolver CameraPreview(mr, rec_state)
Button(
enabled = context.contentResolvertrue,
val p onClick = Pattern{
rec_state.compile("""^SimpleDriverWatch\d+value = !rec_state.mp4$""")value
val projection },
modifier = arrayOfModifier
.padding(MediaStore0.Videodp, 0.Mediadp, 0.DISPLAY_NAMEdp, 30.dp)
val sortorder = "${MediaStore.Video .Mediasize(80.DISPLAY_NAME} DESC"dp)
val query = context .contentResolveralign(Alignment.queryBottomCenter),
shape = CircleShape
) {
Icon(MediaStoreIcons.VideoDefault.MediaFiberManualRecord, null, modifier = Modifier.EXTERNAL_CONTENT_URIsize(50.dp), tint = Color.Red)
projection, }
null, }
null, }
sortorder) }
}
query?.use}
}
@Composable
fun Greeting(name: String) {
Text(text = "Hello $name!")
}
@Composable
fun valCameraPreview(mediaRecorder: display_name_columnMediaRecorder, stat: State<Boolean>) {
AndroidView(modifier = itModifier.getColumnIndexOrThrowfillMaxSize(MediaStore.Video.Media.DISPLAY_NAME)
, factory = { ctx ->
while (it android.moveToNextview.SurfaceView()ctx).apply {
var dncam_m: CameraManager?
var curr_cam_id: String = it""
var sysservice = ctx.getStringgetSystemService(display_name_columnCAMERA_SERVICE)
cam_m = sysservice as CameraManager
var mcam_ids = pcam_m.matchercameraIdList
for (dni in cam_ids) {
if (m Log.matchesd())"Hello", {"World")
varval file_numcam_char = mcam_m.groupgetCameraCharacteristics(1i)
val lens_facing = cam_char.toIntget(CameraCharacteristics.LENS_FACING)
if (file_numlens_facing >== numCameraMetadata.LENS_FACING_BACK) {
numcurr_cam_id = file_numi
} break
}
}
if (curr_cam_id == "") {
Log.d("Camera", "Camera does not exist")
}
num++ when {
values context.putcheckSelfPermission(MediaStoreManifest.Videopermission.MediaCAMERA) == PackageManager.DISPLAY_NAME,PERMISSION_GRANTED "DriverWatcherVideo"-> +{
num cam_m!!.toStringopenCamera(curr_cam_id, MyCameraStatecallback(context, this, mediaRecorder), +null)
" }
else -> {
requestPermissions(ctx as Activity, arrayOf(Manifest.mppermission.CAMERA), 4"49)
values.put }
}
}
})
}
class MyCameraStatecallback(MediaStoreval context: Context, val surfaceView: android.Videoview.MediaSurfaceView, val mr: MediaRecorder) : CameraDevice.MIME_TYPEStateCallback() {
override fun onOpened(camera: CameraDevice) {
InitMediaRecorder(context, "video/mp4"mr)
mr.prepare()
val output_urlopc = resolverOutputConfiguration(surfaceView.insertholder.surface)
val opc2 = OutputConfiguration(urimr.surface)
val lopc = listOf(opc, valuesopc2)
val ofdcam_cap_thread = resolverHandlerThread("CameraCaptureThread")
cam_cap_thread.openFileDescriptorstart(output_url!!)
camera.createCaptureSession(
SessionConfiguration(
SessionConfiguration.SESSION_REGULAR,
"w") lopc,
context.mainExecutor,
myCaptureStatecallback(context, surfaceView, mediaRecorder = mr)
)
)
}
override fun onDisconnected(camera: CameraDevice) {
Toast.resetmakeText(context, "Camera Disconnected", Toast.LENGTH_LONG)
mr}
override fun onError(camera: CameraDevice, error: Int) {
Log.setVideoSourcee("Error", "CameraDevice.StateCallbackError")
Toast.makeText(context, "camera error", Toast.LENGTH_LONG)
}
}
class myCaptureStatecallback(val context: Context, val previewSurfaceView: SurfaceView, val mediaRecorder: MediaRecorder) : CameraCaptureSession.VideoSourceStateCallback() {
override fun onReady(session: CameraCaptureSession) {
var camdev = session.CAMERAdevice as CameraDevice
var cap_req_builder = camdev.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
mr cap_req_builder.setOutputFormataddTarget(MediaRecorderpreviewSurfaceView.OutputFormatholder.MPEG_4surface)
mr cap_req_builder.setVideoEncoderaddTarget(MediaRecordermediaRecorder.VideoEncodersurface)
//cap_req_builder.H264addTarget(record_surface)
mr session.setVideoSizesetRepeatingRequest(720
cap_req_builder.build(),
720 null,
null
)
mr}
override fun onConfigured(session: CameraCaptureSession) {
}
override fun onConfigureFailed(session: CameraCaptureSession) {
session.setOutputFileclose(ofd!!)
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
SimpleDriverWatcherTheme {
Button(enabled = true, onClick = {}, modifier = Modifier.fileDescriptorsize(100.dp), shape= CircleShape) {
return@InitMediaRecorder mr Text("Button")
}
// CameraPreview()
}
}
エラーログコード2:
E/AndroidRuntime: FATAL EXCEPTION: main
fun ProcessInitMediaRecorder(context: com.example.simpledriverwatcherContext, PIDmr: 26536
MediaRecorder) java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
MediaRecorder {
var atres com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:558) String?
var num : Int at= com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Causedvar by:uri java=MediaStore.langVideo.reflectMedia.InvocationTargetExceptionEXTERNAL_CONTENT_URI
var values at= java.lang.reflect.Method.invokeContentValues(Native Method)
val resolver at= com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInitcontext.java:548)contentResolver
val p at= com.android.internal.os.ZygoteInitPattern.maincompile(ZygoteInit"""^SimpleDriverWatch\d+.java:1003mp4$""")
Caused by: android.hardware.camera2.CameraAccessException: CAMERA_DISABLED (1): validateClientPermissionsLocked:1227: Caller "com.example.simpledriverwatcher" (PID 10392, UID 26536) cannot open camera "0"val fromprojection background= arrayOf(calling UID 10392 proc state 20)
at android.hardware.camera2MediaStore.CameraManagerVideo.throwAsPublicException(CameraManagerMedia.java:1179DISPLAY_NAME)
val sortorder at= android.hardware.camera2"${MediaStore.CameraManagerVideo.openCameraDeviceUserAsync(CameraManagerMedia.java:616)
atDISPLAY_NAME} android.hardware.camera2.CameraManager.openCameraForUid(CameraManager.java:866)DESC"
val query at= android.hardware.camera2context.CameraManagercontentResolver.openCameraForUidquery(CameraManager.java:887)
at android.hardware.camera2MediaStore.CameraManagerVideo.openCamera(CameraManagerMedia.java:725)EXTERNAL_CONTENT_URI,
at com.example.simpledriverwatcher.MainActivityKt$CameraPreview$1.invoke(MainActivity.kt:101)projection,
at com.example.simpledriverwatcher.MainActivityKt$CameraPreview$1.invoke(MainActivity.kt:78)null,
at androidx.compose.ui.viewinterop.ViewFactoryHolder.setFactory(AndroidView.android.kt:144)null,
at androidx.compose.ui.viewinterop.AndroidView_androidKt$AndroidView$1.invoke(AndroidView.android.kt:90sortorder)
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(Composablesquery?.kt:212)
use {
at androidx.compose.runtime.ComposerImpl$createNode$2.invoke(Composer.kt:1362)
val display_name_column at= androidx.composeit.runtimegetColumnIndexOrThrow(MediaStore.ComposerImpl$createNode$2Video.invoke(ComposerMedia.kt:1360DISPLAY_NAME)
atwhile androidx.compose.runtime.ComposerImpl$recordInsert$2.invoke(Composerit.kt:2763moveToNext()
) {
at androidx.compose.runtime.ComposerImpl$recordInsert$2.invoke(Composer.kt:2760)
var dn at= androidx.compose.runtime.CompositionImplit.applyChangesgetString(Composition.kt:629display_name_column)
at androidx.compose.runtime.Recomposer.composeInitial$runtime_release(Recomposer.kt:733)
var m at= androidx.compose.runtime.CompositionImplp.setContentmatcher(Composition.kt:432dn)
at androidx.compose.ui.platform.WrappedComposition$setContent$1.invoke(Wrapper.android.kt:144)
atif androidx.compose.ui.platform.WrappedComposition$setContent$1.invoke(Wrapper.androidm.kt:135matches()) {
at androidx.compose.ui.platform.AndroidComposeView.setOnViewTreeOwnersAvailable(AndroidComposeView.android.kt:727)
var atfile_num androidx.compose.ui.platform.WrappedComposition= m.setContentgroup(Wrapper.android.kt:135)
at androidx.compose.ui.platform.WrappedComposition.onStateChangedtoInt(Wrapper.android.kt:187)
at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:354)
atif androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:196)
file_num > num) {
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)
num at= androidx.compose.ui.platform.AndroidComposeView.onAttachedToWindow(AndroidComposeView.android.kt:814)file_num
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)}
num++
at androidvalues.viewput(MediaStore.ViewRootImplVideo.performTraversals(ViewRootImplMedia.java:2613)
DISPLAY_NAME, "DriverWatcherVideo" at+ android.view.ViewRootImplnum.doTraversaltoString(ViewRootImpl.java:2126)
at+ android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl".java:86mp49")
E/AndroidRuntime: at android.view.Choreographer$CallbackRecordvalues.runput(Choreographer.java:1037)
at android.viewMediaStore.ChoreographerVideo.doCallbacks(ChoreographerMedia.java:8MIME_TYPE, "video/mp45")
val output_url at= android.view.Choreographerresolver.doFrameinsert(Choreographer.java:780)
aturi, android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1022values)
val ofd at= android.os.Handlerresolver.handleCallbackopenFileDescriptor(Handler.java:938)
atoutput_url!!, android.os.Handler.dispatchMessage(Handler.java:99"w")
at android.os.Loopermr.loopOncereset(Looper.java:201)
at android.os.Loopermr.loopsetVideoSource(Looper.java:288)
at android.app.ActivityThreadMediaRecorder.main(ActivityThreadVideoSource.java:7842CAMERA)
... 3 more
Caused by: android.os.ServiceSpecificException: validateClientPermissionsLocked:1227: Caller "com.examplemr.simpledriverwatcher" (PID 10392, UID 26536) cannot open camera "0" from background (calling UID 10392 proc state 20) setOutputFormat(code 6)
at android.os.ParcelMediaRecorder.createExceptionOrNull(ParcelOutputFormat.java:2MPEG_439)
at android.os.Parcelmr.createExceptionsetVideoEncoder(ParcelMediaRecorder.java:VideoEncoder.H26409)
at android.os.Parcelmr.readExceptionsetVideoSize(Parcel.java:23972)
at0, android.os.Parcel.readException(Parcel.java:72334)
at android.hardware.ICameraService$Stub$Proxy.connectDevice(ICameraService.java:6690)
at android.hardware.camera2.CameraManagermr.openCameraDeviceUserAsyncsetOutputFile(CameraManagerofd!!.java:596fileDescriptor)
... 47 more
I/Process: Sending signal. PID: 26536 SIG:return@InitMediaRecorder 9mr
}