您可以使用Java轻松生成采样的声音数据并进行播放,而无需使用本机代码。如果您正在谈论MIDI,可能会遇到一些棘手的问题,但是我还没有涉足该领域。
要生成采样的声音数据,您必须将过程倒退。我们将采取类似于A-to-D的方式,并随时间采样连续的声音功能。您的声卡对通过麦克风或线路输入的音频执行相同的操作。
首先,选择一个采样率(不是我们正在生成的音调的频率)。让我们以44100
Hz为例,因为这可能是声卡的播放速率(因此没有采样率转换,除非硬件做到这一点,否则并不容易)。
// in hz, number of samples in one secondsampleRate = 44100// this is the time BETWEEN SamplessamplePeriod = 1.0 / sampleRate// 2msduration = 0.002;durationInSamples = Math.ceil(duration * sampleRate);time = 0;for(int i = 0; i < durationInSamples; i++){ // sample a sine wave at 440 hertz at each time tick // substitute a function that generates a sawtooth as a function of time / freq // rawOutput[i] = function_of_time(other_relevant_info, time); rawOutput[i] = Math.sin(2 * Math.PI * 440 * time); time += samplePeriod;}// now you can playback the rawOutput// streaming this may be trickier


