diff --git a/src/main/java/envoy/client/data/AudioRecorder.java b/src/main/java/envoy/client/data/AudioRecorder.java new file mode 100644 index 0000000..96b08a0 --- /dev/null +++ b/src/main/java/envoy/client/data/AudioRecorder.java @@ -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. + *

+ * Project: envoy-client
+ * File: AudioRecorder.java
+ * Created: 02.07.2020
+ * + * @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); + } + } +}