Kotlin ile Kamera Kullanımı Örneği (Sinematik Çekimler İçin)
Aşağıda Android'de kamera kullanarak sinematik çekimler yapmak için temel bir Kotlin örneği bulunmaktadır. Bu örnek, CameraX kütüphanesini kullanmaktadır.
1. Öncelikle build.gradle dosyasına bağımlılıkları ekleyin:
dependencies { // CameraX core library implementation "androidx.camera:camera-core:1.3.0" implementation "androidx.camera:camera-camera2:1.3.0" implementation "androidx.camera:camera-lifecycle:1.3.0" implementation "androidx.camera:camera-view:1.3.0" implementation "androidx.camera:camera-extensions:1.3.0" // Diğer gerekli bağımlılıklar implementation "androidx.constraintlayout:constraintlayout:2.1.4" implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.6.2" }
2. AndroidManifest.xml dosyasına izinleri ekleyin:
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" />
3. Kamera önizleme ve video kaydı için Kotlin kodu:
import android.content.ContentValues import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.CameraSelector import androidx.camera.core.Preview import androidx.camera.video.* import androidx.camera.view.PreviewView import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class CinematicCameraActivity : AppCompatActivity() { private lateinit var previewView: PreviewView private var videoCapture: VideoCapture<Recorder>? = null private var recording: Recording? = null private lateinit var cameraExecutor: ExecutorService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_cinematic_camera) previewView = findViewById(R.id.previewView) // Kamera izinlerini kontrol et if (allPermissionsGranted()) { startCamera() } else { ActivityCompat.requestPermissions( this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS ) } cameraExecutor = Executors.newSingleThreadExecutor() } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission( baseContext, it) == PackageManager.PERMISSION_GRANTED } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener({ // Kamerayı bağlamak için kullanılacak provider val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() // Önizleme ayarları val preview = Preview.Builder() .build() .also { it.setSurfaceProvider(previewView.surfaceProvider) } // Video kaydı için ayarlar (sinematik ayarlar) val recorder = Recorder.Builder() .setQualitySelector(QualitySelector.from(Quality.UHD)) .build() videoCapture = VideoCapture.withOutput(recorder) // Arka kamerayı seç val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try { // Önceki bağlantıları temizle cameraProvider.unbindAll() // Kamerayı bağla cameraProvider.bindToLifecycle( this, cameraSelector, preview, videoCapture) } catch(exc: Exception) { Log.e(TAG, "Camera binding failed", exc) } }, ContextCompat.getMainExecutor(this)) } fun startRecording() { val videoCapture = this.videoCapture ?: return val currentRecording = recording if (currentRecording != null) { // Zaten kayıt yapılıyor return } // Yeni kayıt oluştur val name = "CinematicVideo-${System.currentTimeMillis()}" val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, name) put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/CinematicApp") } } val mediaStoreOutputOptions = MediaStoreOutputOptions .Builder(contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) .setContentValues(contentValues) .build() recording = videoCapture.output .prepareRecording(this, mediaStoreOutputOptions) .apply { // Ses kaydını etkinleştir withAudioEnabled() // Kayıt kalitesi için callback addListener(Runnable { Toast.makeText(baseContext, "Sinematik kayıt başladı", Toast.LENGTH_SHORT).show() }, ContextCompat.getMainExecutor(this@CinematicCameraActivity)) } .start(ContextCompat.getMainExecutor(this)) { recordEvent -> when(recordEvent) { is VideoRecordEvent.Start -> { // Kayıt başladı } is VideoRecordEvent.Finalize -> { if (!recordEvent.hasError()) { val msg = "Video kaydedildi: ${recordEvent.outputResults.outputUri}" Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT) .show() } else { recording?.close() recording = null Log.e(TAG, "Video kaydı başarısız: ${recordEvent.error}") } } } } } fun stopRecording() { recording?.stop() recording = null } override fun onDestroy() { super.onDestroy() cameraExecutor.shutdown() } companion object { private const val TAG = "CinematicCamera" private const val REQUEST_CODE_PERMISSIONS = 10 private val REQUIRED_PERMISSIONS = arrayOf( android.Manifest.permission.CAMERA, android.Manifest.permission.RECORD_AUDIO ) } }
4. XML layout dosyası (activity_cinematic_camera.xml):
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.camera.view.PreviewView android:id="@+id/previewView" android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android:id="@+id/recordButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Kayıt" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Sinematik Efektler İçin Ekstra Ayarlar
Daha sinematik bir görünüm için aşağıdaki ayarları ekleyebilirsiniz:
Frame Rate Kontrolü:
val recorder = Recorder.Builder() .setQualitySelector(QualitySelector.from(Quality.UHD)) .setFrameRate(24) // Sinematik 24 fps .build()
Bitrate Ayarları:
val videoOutputOptions = FileOutputOptions.Builder(outputFile) .setVideoEncodingBitRate(50_000_000) // Yüksek bitrate .build()
Stabilizasyon:
val cameraProvider = cameraProviderFuture.get() val cameraInfo = cameraProvider.getCameraInfo(cameraSelector) if (cameraInfo.isVideoStabilizationSupported) { cameraInfo.setVideoStabilizationMode(VideoStabilizationMode.HIGH) }
Bu örnek, temel bir sinematik kamera uygulaması için başlangıç noktasıdır. Profesyonel sonuçlar için ekstra özellikler (manuel odak, pozlama, beyaz dengesi kontrolleri vb.) eklemeniz gerekebilir.
0 Yorumlar