Compare commits

..
Author SHA1 Message Date
nutzma75019 316e19236f TextureView anstatt SurfaceView 2023-06-21 09:19:03 +02:00
nutzma75019 b337d86655 Wenn Permission erteilt, wird die Aufzeichnung direkt von der Funktion onRequestPermissionsResult gestartet.
Fehlerbehebung in Zeile 61: if (requestCode == REQUEST_PERMISSION) {
davor: if (requestCode == REQUEST_PERMISSIONS) {
2023-06-19 21:09:16 +02:00
nutzma75019 18eb62b034 Implementierung einer Runnable Class mit Preview in einer SurfaceView in der MainActivity 2023-06-18 17:22:55 +02:00
nutzma75019 23ac26d0a4 Aufzeichnung von Video und Ton in MainActivity
ToDo: in Fragment aufrufen
ToDo: Gespeichertes Video um 90° gedreht
2023-06-17 12:15:39 +02:00
Tinzch67102 518e207032 Runnable test implementation 2023-06-17 10:33:54 +02:00
nutzma75019 7ed3408d01 Aufzeichnung von Video und Ton in MainActivity
ToDo: in Fragment aufrufen
ToDo: Gespeichertes Video um 90° gedreht
2023-06-16 20:34:15 +02:00
15 changed files with 398 additions and 159 deletions

No files matched your search

-7
View File
@@ -25,7 +25,6 @@ android {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
namespace 'com.example.greenwatch'
}
dependencies {
@@ -36,10 +35,4 @@ dependencies {
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
def camerax_version = "1.2.3"
implementation "androidx.camera:camera-camera2:${camerax_version}"
implementation "androidx.camera:camera-lifecycle:${camerax_version}"
implementation "androidx.camera:camera-view:${camerax_version}"
}
+7 -11
View File
@@ -1,14 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.greenwatch">
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.camera"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
@@ -26,9 +25,6 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".KameraAktivitaet" />
</application>
</manifest>
@@ -0,0 +1,225 @@
package com.example.greenwatch;
import android.graphics.SurfaceTexture;
import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.view.Surface;
import android.view.SurfaceHolder;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
public class AlarmRecorder {
private String videoPath;
private String audioPath;
private MediaFormat videoFormat;
private MediaFormat audioFormat;
private MediaExtractor videoExtractor;
private MediaExtractor audioExtractor;
private Runnable audioRecorderRunnable;
private Runnable videoRecorderRunnable;
private MediaRecorder videoRecorder;
private MediaRecorder audioRecorder;
//private SurfaceHolder previewHolder;
private Surface surface;
private Thread videoThread; // Video-Thread als Instanzvariable
private Thread audioThread; // Audio-Thread als Instanzvariable
public AlarmRecorder(SurfaceTexture surfaceTexture) {
audioRecorder = new MediaRecorder();
videoRecorder = new MediaRecorder();
videoExtractor = new MediaExtractor();
audioExtractor = new MediaExtractor();
this.surface = new Surface(surfaceTexture);
}
public void startRecording() {
createStoragePaths(); //Speicherort und -namen für Audio- und Video-Datei
audioRecorderRunnable = new AudioRecorder(audioRecorder, audioPath);
videoRecorderRunnable = new VideoRecorder(videoRecorder, videoPath, surface);
audioThread = new Thread(audioRecorderRunnable);
videoThread = new Thread(videoRecorderRunnable);
//Threads starten
videoThread.start();
audioThread.start();
}
public void stopRecording() {
try {
stopVideoRecording();
stopAudioRecording();
waitTillThreadsStopped();
File videoFile = new File(videoPath); //Speichere das aufgenommene Video
File audioFile = new File(audioPath); //Speichere die aufgenommene Audio
if (videoFile.exists() && audioFile.exists()) {
//Wenn Video- und Audioaufzeichnung gestoppt und abgespeichert sind, beginne mit dem Mergeprozess der beiden
mergeVideoWithAudio();
}
} catch (RuntimeException stopException) {
stopException.printStackTrace();
}
}
private void createStoragePaths(){
//Pfade zum Zwischenspeichern der aufgenommenen Audio und Video-Datei
String externalStorageDirectory = Environment.getExternalStorageDirectory().getAbsolutePath();
String dcimDirectory = externalStorageDirectory + "/DCIM";
videoPath = dcimDirectory + "/video.mp4";
audioPath = dcimDirectory + "/audio.mp3";
}
private void stopVideoRecording(){
if (videoRecorder != null) {
videoRecorder.stop();
videoRecorder.release();
videoRecorder = null;
}
}
private void stopAudioRecording(){
if (audioRecorder != null) {
audioRecorder.stop();
audioRecorder.release();
audioRecorder = null;
}
}
private void waitTillThreadsStopped(){
try {
videoThread.join();
audioThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void mergeVideoWithAudio() {
try {
setVideoExtractorDataSource(); //extrahieren der Video Datei, die zuvor zwischengespeichert wurde
setAudioExtractorDataSource(); //extrahieren der Audio Datei, die zuvor zwischengespeichert wurde
//Speicherort der später zusammengeführten Datei
String outputFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath() + "/merged_video.mp4";
//MediaMuxer zum Zusammenführen einer Audio- und einer Videodatei
MediaMuxer muxer = new MediaMuxer(outputFilePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
int videoTrack = muxer.addTrack(videoFormat);
int audioTrack = muxer.addTrack(audioFormat);
muxer.start();
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
videoExtraction(buffer, videoTrack, bufferInfo, muxer);
audioExtraction(buffer, audioTrack, bufferInfo, muxer);
muxer.stop();
muxer.release();
// Löschen der separaten Video- und Audio-Dateien
deleteVideoFile();
deleteAudioFile();
} catch (IOException e) {
e.printStackTrace();
}
}
private void setVideoExtractorDataSource() {
try {
videoExtractor.setDataSource(videoPath);
int videoTrackIndex = getTrackIndex(videoExtractor, "video/");
if (videoTrackIndex < 0) {
// Video-Track nicht gefunden
return;
}
videoExtractor.selectTrack(videoTrackIndex);
videoFormat = videoExtractor.getTrackFormat(videoTrackIndex);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void setAudioExtractorDataSource() {
try {
audioExtractor.setDataSource(audioPath);
int audioTrackIndex = getTrackIndex(audioExtractor, "audio/");
if (audioTrackIndex < 0) {
// Audio-Track nicht gefunden
return;
}
audioExtractor.selectTrack(audioTrackIndex);
audioFormat = audioExtractor.getTrackFormat(audioTrackIndex);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private int getTrackIndex(MediaExtractor extractor, String mimeType) {
int trackCount = extractor.getTrackCount();
for (int i = 0; i < trackCount; i++) {
MediaFormat format = extractor.getTrackFormat(i);
String trackMimeType = format.getString(MediaFormat.KEY_MIME);
if (trackMimeType.startsWith(mimeType)) {
return i;
}
}
return -1;
}
private void videoExtraction(ByteBuffer buffer, int videoTrack, MediaCodec.BufferInfo bufferInfo, MediaMuxer muxer) {
videoExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
while (true) {
int sampleSize = videoExtractor.readSampleData(buffer, 0);
if (sampleSize < 0) {
break;
}
long presentationTimeUs = videoExtractor.getSampleTime();
bufferInfo.offset = 0;
bufferInfo.size = sampleSize;
bufferInfo.flags = MediaCodec.BUFFER_FLAG_KEY_FRAME;
bufferInfo.presentationTimeUs = presentationTimeUs;
muxer.writeSampleData(videoTrack, buffer, bufferInfo);
videoExtractor.advance();
}
}
private void audioExtraction(ByteBuffer buffer, int audioTrack, MediaCodec.BufferInfo bufferInfo, MediaMuxer muxer) {
audioExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
while (true) {
int sampleSize = audioExtractor.readSampleData(buffer, 0);
if (sampleSize < 0) {
break;
}
long presentationTimeUs = audioExtractor.getSampleTime();
bufferInfo.offset = 0;
bufferInfo.size = sampleSize;
bufferInfo.flags = 0; // or MediaCodec.BUFFER_FLAG_KEY_FRAME
bufferInfo.presentationTimeUs = presentationTimeUs;
muxer.writeSampleData(audioTrack, buffer, bufferInfo);
audioExtractor.advance();
}
}
private void deleteVideoFile(){
File videoFile = new File(videoPath);
if (videoFile.exists()) {
videoFile.delete();
}
}
private void deleteAudioFile(){
File audioFile = new File(audioPath);
if (audioFile.exists()) {
audioFile.delete();
}
}
}
@@ -0,0 +1,30 @@
package com.example.greenwatch;
import android.media.MediaRecorder;
import java.io.IOException;
public class AudioRecorder implements Runnable {
private final MediaRecorder audioRecorder;
private final String audioPath;
public AudioRecorder(MediaRecorder audioRecorder, String audioPath) {
this.audioRecorder = audioRecorder;
this.audioPath = audioPath;
}
@Override
public void run() {
audioRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
audioRecorder.setOutputFile(audioPath);
try {
audioRecorder.prepare();
audioRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -1,4 +0,0 @@
package com.example.greenwatch;
public class Beschleunigungssensor {
}
@@ -1,4 +0,0 @@
package com.example.greenwatch;
public class Kamera {
}
@@ -1,59 +0,0 @@
package com.example.greenwatch;
import android.graphics.ImageFormat;
import android.media.Image;
import android.os.Bundle;
import android.util.Size;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.ExecutionException;
public class KameraAktivitaet extends AppCompatActivity {
private PreviewView previewView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_kamera2_nebenaktivitaet);
previewView = findViewById(R.id.previewView);
final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
bindImageAnalysis(cameraProviderFuture.get());
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}, ContextCompat.getMainExecutor(this));
}
private void bindImageAnalysis(ProcessCameraProvider cameraProvider) {
ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
builder.setTargetResolution(new Size(640, 480));
builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST);
ImageAnalysis imageAnalysis = builder.build();
imageAnalysis.setAnalyzer(
ContextCompat.getMainExecutor(this),
imageProxy -> {
int imageFormat = imageProxy.getFormat();
if (imageFormat == ImageFormat.YUV_420_888) {
Image image = imageProxy.getImage();
}
imageProxy.close();
});
Preview preview = new Preview.Builder().build();
CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
cameraProvider.bindToLifecycle(this, cameraSelector, imageAnalysis, preview);
}
}
@@ -1,40 +1,101 @@
package com.example.greenwatch;
import android.content.Intent;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int RECHTEANFORDERUNG_KAMERA = 10;
public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener{
private boolean isRecording = false;
private static final int REQUEST_PERMISSION = 200;
private Button button;
private TextureView textureView;
private AlarmRecorder alarmRecorder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button kameraStarten = findViewById(R.id.button_camera);
kameraStarten.setOnClickListener(v -> {
if (istZugriffAufKameraErlaubt()) {
starteKameraAktivitaet();
} else {
zugriffAufKameraAnfordern();
button = findViewById(R.id.button);
textureView = findViewById(R.id.textureView);
textureView.setSurfaceTextureListener(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isRecording) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
REQUEST_PERMISSION);
} else {
isRecording = true;
alarmRecorder.startRecording();
}
} else {
isRecording = false;
alarmRecorder.stopRecording();
}
}
});
}
private boolean istZugriffAufKameraErlaubt() {
return ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
alarmRecorder = new AlarmRecorder(surfaceTexture);
}
private void zugriffAufKameraAnfordern() {
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.CAMERA}, RECHTEANFORDERUNG_KAMERA);
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Die Größe der SurfaceTexture hat sich geändert
// Hier können entsprechende Anpassungen vorgenommen werden
}
private void starteKameraAktivitaet() {
startActivity(new Intent(this, KameraAktivitaet.class));
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
// SurfaceTexture wurde zerstört
// Hier können entsprechende Bereinigungen durchgeführt werden
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
// SurfaceTexture wurde aktualisiert
// Hier können entsprechende Aktionen ausgeführt werden, wenn gewünscht
}
private SurfaceTexture getSurfaceTexture() {
return textureView.getSurfaceTexture();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Berechtigungen wurden gewährt
Toast.makeText(this, "Berechtigungen gewährt", Toast.LENGTH_SHORT).show();
isRecording = true;
alarmRecorder.startRecording();
} else {
// Berechtigungen wurden nicht gewährt
Toast.makeText(this, "Berechtigungen nicht gewährt", Toast.LENGTH_SHORT).show();
}
}
}
}
@@ -1,4 +0,0 @@
package com.example.greenwatch;
public class Mikrofon {
}
@@ -0,0 +1,39 @@
package com.example.greenwatch;
import android.media.MediaRecorder;
import android.view.Surface;
import android.view.SurfaceHolder;
import java.io.IOException;
public class VideoRecorder implements Runnable{
private final MediaRecorder videoRecorder;
private final String videoPath;
//private SurfaceHolder previewHolder;
private Surface surface;
public VideoRecorder(MediaRecorder videoRecorder, String videoPath, Surface surface) {
this.videoRecorder = videoRecorder;
this.videoPath = videoPath;
this.surface = surface;
}
@Override
public void run() {
videoRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
videoRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
videoRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
videoRecorder.setOutputFile(videoPath);
videoRecorder.setOrientationHint(90);
videoRecorder.setPreviewDisplay(surface);
try {
videoRecorder.prepare();
videoRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -1,41 +0,0 @@
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".KameraAktivitaet">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/erklaerung">
<androidx.camera.view.PreviewView
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/alarm"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="" />
<TextView
android:id="@+id/luminanz"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:textSize="100sp"
android:textColor="#9999ff"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
+17 -8
View File
@@ -6,17 +6,26 @@
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button_camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kamera starten"
<TextureView
android:id="@+id/textureView"
android:layout_width="1sp"
android:layout_height="1sp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.129"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.931" />
app:layout_constraintTop_toBottomOf="@id/button"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="339dp"
android:text="Record Video"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
+2 -2
View File
@@ -1,7 +1,7 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '8.0.0' apply false
id 'com.android.library' version '8.0.0' apply false
id 'com.android.application' version '7.1.3' apply false
id 'com.android.library' version '7.1.3' apply false
}
task clean(type: Delete) {
+1 -3
View File
@@ -18,6 +18,4 @@ android.useAndroidX=true
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.defaults.buildfeatures.buildconfig=true
android.nonFinalResIds=false
android.nonTransitiveRClass=true
+1 -1
View File
@@ -1,6 +1,6 @@
#Thu May 11 14:50:16 CEST 2023
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME