最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Realtime generation of audio to write to `SourceDataLine` - Stack Overflow

programmeradmin1浏览0评论

I'm wondering if it's possible to constantly output audio generated on the fly to a DataLine, e.g. so the sound changes in response to some kind of state like user input. I'm at a point where I can write indefinitely to the line, but I am just constantly writing nonstop rather than as needed to keep only a short buffer of extra audio written. Is there an approach to do so, other than perhaps just calling Thread.sleep in the loop for the duration of the buffer?

import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import javax.sound.sampled.*
import kotlin.math.PI
import kotlin.math.sin

const val SAMPLING_RATE = 44100F
const val BITS16 = 16
const val STEREO = 2
val format = AudioFormat(
    AudioFormat.Encoding.PCM_SIGNED,
    SAMPLING_RATE,
    BITS16,
    STEREO,
    BITS16 * STEREO / 8,
    SAMPLING_RATE * BITS16 * STEREO / 8,
    false)
const val BUFFER_SIZE = 4096


var phase = 0F
fun generateBuffer(n: Int, buffer: FloatBuffer) {
    // Some potentially state-sensitive audio generation procedure. Generating a pure sine as an example.
    repeat(n) {buffer.put(sin((phase + it * 2 * PI * 440 / 44100F).toFloat()))}
    phase += (n * 2 * PI * 440 / 44100F).toFloat()
}

fun main() {
    val dataLineInfo = DataLine.Info(
        SourceDataLine::class.java,
        format)
    val dataLine = AudioSystem.getLine(dataLineInfo) as SourceDataLine
    dataLine.open()
    val byteBuffer = ByteBuffer.allocate(2 * 2 * BUFFER_SIZE).order(ByteOrder.LITTLE_ENDIAN)
    val intBuffer = byteBuffer.asIntBuffer()
    val floatBuffer = FloatBuffer.allocate(BUFFER_SIZE)
    dataLine.start()

    // This just generates and writes data nonstop. Can I generate chunks of audio on-demand as they are exhausted?
    while (true) {
        floatBuffer.rewind()
        generateBuffer(BUFFER_SIZE, floatBuffer)
        floatBuffer.rewind()
        intBuffer.rewind()
        repeat(BUFFER_SIZE) { intBuffer.put((floatBuffer.get() * 32767).toInt()) }
        dataLine.write(byteBuffer.array(), 0, 2 * 2 * BUFFER_SIZE)
    }
}
发布评论

评论列表(0)

  1. 暂无评论