|
|
|
|
|
|
|
|
|
|
|
package com.example.ueberwachungssystem.Detection; |
|
|
|
|
|
|
|
|
|
|
|
import android.content.Context; |
|
|
|
|
|
import android.media.MediaPlayer; |
|
|
|
|
|
import android.media.MediaRecorder; |
|
|
|
|
|
|
|
|
|
|
|
import java.io.File; |
|
|
|
|
|
import java.io.IOException; |
|
|
|
|
|
import java.time.LocalDateTime; |
|
|
|
|
|
import java.time.format.DateTimeFormatter; |
|
|
|
|
|
|
|
|
|
|
|
public class AudioRecorder { |
|
|
|
|
|
private final Context context; |
|
|
|
|
|
private MediaRecorder mediaRecorder = null; |
|
|
|
|
|
private boolean isRecording = false; |
|
|
|
|
|
private File outputDir; // Default: in app files directory |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public AudioRecorder (Context context) { |
|
|
|
|
|
this.context = context; |
|
|
|
|
|
this.outputDir = context.getFilesDir(); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
public void startRecording() { |
|
|
|
|
|
// Handle logic |
|
|
|
|
|
if (outputDir == null) |
|
|
|
|
|
return; |
|
|
|
|
|
if (isRecording) |
|
|
|
|
|
return; |
|
|
|
|
|
isRecording = true; |
|
|
|
|
|
|
|
|
|
|
|
// Setup Audio Recorder for output Format: 3GP |
|
|
|
|
|
mediaRecorder = new MediaRecorder(); |
|
|
|
|
|
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); |
|
|
|
|
|
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); |
|
|
|
|
|
mediaRecorder.setOutputFile(outputDir + "/" + generateFileName() + ".3gp"); |
|
|
|
|
|
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); |
|
|
|
|
|
try { |
|
|
|
|
|
mediaRecorder.prepare(); |
|
|
|
|
|
} catch (IOException e) { |
|
|
|
|
|
e.printStackTrace(); |
|
|
|
|
|
} |
|
|
|
|
|
mediaRecorder.start(); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
public void stopRecording() { |
|
|
|
|
|
if (mediaRecorder != null) { |
|
|
|
|
|
mediaRecorder.stop(); |
|
|
|
|
|
mediaRecorder.reset(); |
|
|
|
|
|
mediaRecorder.release(); |
|
|
|
|
|
mediaRecorder = null; |
|
|
|
|
|
isRecording = false; |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
public boolean isRecording(){ |
|
|
|
|
|
return isRecording; |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
public void setOutputDir(File outputDir) { |
|
|
|
|
|
this.outputDir = outputDir; |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
private String generateFileName(){ |
|
|
|
|
|
// Get the current timestamp |
|
|
|
|
|
LocalDateTime currentTime = LocalDateTime.now(); |
|
|
|
|
|
// Define the format for the timestamp |
|
|
|
|
|
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"); |
|
|
|
|
|
// Return the timestamp as a string |
|
|
|
|
|
return currentTime.format(formatter); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
public void playAudio() { |
|
|
|
|
|
MediaPlayer mp = new MediaPlayer(); |
|
|
|
|
|
try { |
|
|
|
|
|
mp.setDataSource(context.getFilesDir() + "/audio.3gp"); |
|
|
|
|
|
mp.prepare(); |
|
|
|
|
|
mp.start(); |
|
|
|
|
|
} catch (Exception e) { |
|
|
|
|
|
e.printStackTrace(); |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
} |