我正在为一个大学项目创建一个小型的听力测试应用程序。我一直在使用以下代码:
Playing an arbitrary tone with Android
到目前为止,我已经为按钮设置了一个switch语句,因此每次单击它时,它都会播放频率越来越高的音调。但是,当达到4000Hz时,声音将不再播放,有人有任何想法吗?谢谢!
公共(public)类AutoTest扩展MainActivity {
private final int duration = 5; // seconds
private final int sampleRate = 8000;
private final int numSamples = duration * sampleRate;
private final double sample[] = new double[numSamples];
private double freqOfTone = 250; // hz
private int inc=0;
int count = 0;
private final byte generatedSnd[] = new byte[2 * numSamples];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_auto_test);
}
void genTone(){
// fill out the array
for (int i = 0; i < numSamples; ++i) {
// sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/(freqOfTone+inc)));
sample[i] = Math.sin((freqOfTone+inc) * 2 * Math.PI * i / (sampleRate));
}
// convert to 16 bit pcm sound array
// assumes the sample buffer is normalised.
int idx = 0;
int ramp = numSamples / 20;
for (int i = 0; i < ramp; i++) {
// scale to maximum amplitude
final short val = (short) ((sample[i] * 32767) * i / ramp);
// in 16 bit wav PCM, first byte is the low order byte
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
}
for (int i = ramp; i < numSamples - ramp; i++) {
// scale to maximum amplitude
final short val = (short) ((sample[i] * 32767));
// in 16 bit wav PCM, first byte is the low order byte
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
}
for (int i = numSamples - ramp; i < numSamples; i++) {
// scale to maximum amplitude
final short val = (short) ((sample[i] * 32767) * (numSamples - i) / ramp);
// in 16 bit wav PCM, first byte is the low order byte
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
}
}
void playSound(){
final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length,
AudioTrack.MODE_STREAM);
audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();
}
public void playTone(View view)
{
//switch statement - auto - increment
switch(count) {
case 0:
break;
case 1:
inc+=250;
break;
case 2:
inc+=500;
break;
case 3:
inc+=1000;
break;
case 4:
inc+=2000;
break;
case 5:
inc+=2000;
break;
case 6:
inc+=2000;
break;
default:
Log.d("Values","error message");
break;
}
genTone();
playSound();
Log.d("Values","This is the value of count"+ count);
count++;
这是我的代码,我将不胜感激任何帮助!
最佳答案
您的采样率为8 kHz-
private final int sampleRate = 8000;
由于采样定理,
sample-rate/2
以上的所有频率都将开始混叠。这意味着在4000 Hz时,您实际上听到的是0 Hz。在4001 Hz时,您听到的是1 Hz。等。如果您将来有兴趣学习更多信号处理,请访问Wiki页面:Wikipedia - Aliasing
尝试将采样率更改为更高的采样率(标准44.1 kHz),这样就可以解决问题!