Created
November 24, 2023 18:09
-
-
Save demoth/4e54d02d448b8fe32df95777be53203d to your computer and use it in GitHub Desktop.
Simple Echo program that directly plays audio captured from the microphone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileOutputStream | |
import java.io.IOException | |
import java.io.InputStream | |
import java.io.OutputStream | |
import javax.sound.sampled.* | |
import kotlin.concurrent.thread | |
import kotlin.system.exitProcess | |
fun main() { | |
val format = AudioFormat(16000.0f, 16, 1, true, true) | |
val captureInfo = DataLine.Info(TargetDataLine::class.java, format) | |
val playbackInfo = DataLine.Info(SourceDataLine::class.java, format) | |
// Check if system supports the data line | |
if (!AudioSystem.isLineSupported(captureInfo) || !AudioSystem.isLineSupported(playbackInfo)) { | |
println("Line not supported") | |
exitProcess(0) | |
} | |
val microphone = AudioSystem.getLine(captureInfo) as TargetDataLine | |
val speakers = AudioSystem.getLine(playbackInfo) as SourceDataLine | |
microphone.open(format) | |
speakers.open(format) | |
microphone.start() | |
speakers.start() | |
var capturing = true | |
// Create a thread to capture the microphone data into a buffer and then write to the output stream for playback | |
thread { | |
try { | |
var numBytesRead: Int | |
val data = ByteArray(microphone.bufferSize / 5) | |
while (true) { | |
// Read the next chunk of data from the TargetDataLine. | |
numBytesRead = microphone.read(data, 0, data.size) | |
// Save this chunk of data. | |
speakers.write(data, 0, numBytesRead) | |
if (!capturing) break | |
} | |
} catch (e: java.lang.Exception) { | |
e.printStackTrace() | |
} | |
} | |
println("Press ENTER to finish.") | |
System.`in`.read() | |
capturing = false | |
microphone.close() | |
speakers.close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment