Add AudioRecorder

This commit is contained in:
Kai S. K. Engelbart 2020-07-03 14:17:04 +02:00
parent cf84dd33b6
commit 0abd5cf17c
No known key found for this signature in database
GPG Key ID: 0A48559CA32CB48F

View File

@ -0,0 +1,68 @@
package envoy.client.data;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.sound.sampled.*;
import envoy.exception.EnvoyException;
/**
* Records audio and exports it as a byte array.
* <p>
* Project: <strong>envoy-client</strong><br>
* File: <strong>AudioRecorder.java</strong><br>
* Created: <strong>02.07.2020</strong><br>
*
* @author Kai S. K. Engelbart
* @since Envoy Client v0.1-beta
*/
public final class AudioRecorder {
private final AudioFormat format;
private DataLine.Info info;
private TargetDataLine line;
private Path tempFile;
public AudioRecorder() { this(new AudioFormat(16000, 16, 1, true, false)); }
public AudioRecorder(AudioFormat format) {
this.format = format;
info = new DataLine.Info(TargetDataLine.class, format);
}
public boolean isSupported() { return AudioSystem.isLineSupported(info); }
public void start() throws EnvoyException {
try {
// Open the line
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
// Prepare temp file
tempFile = Files.createTempFile("recording", "wav");
// Start the recording
var ais = new AudioInputStream(line);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, tempFile.toFile());
} catch (IOException | LineUnavailableException e) {
throw new EnvoyException("Cannot record voice", e);
}
}
public byte[] finish() throws EnvoyException {
try {
line.stop();
line.close();
byte[] data = Files.readAllBytes(tempFile);
Files.delete(tempFile);
return data;
} catch (IOException e) {
throw new EnvoyException("Cannot save voice recording", e);
}
}
}