我正在为大学项目创建一个小型听力测试应用程序。我一直在使用以下代码: Playing an arbitrary tone with Android
到目前为止,我有一个带有switch语句的按钮,因此每次单击它时,它都会播放频率增加的音调。然而,当它达到4000Hz时声音将不再播放,有没有人有任何想法?谢谢!
公共类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++;
这是我的代码,我非常感谢任何帮助!
答案 0 :(得分:1)
您的采样率为8 kHz -
private final int sampleRate = 8000;
由于采样定理,sample-rate/2
以上的所有频率都将开始混叠。这意味着在4000赫兹时你实际听到0赫兹。在4001赫兹,你听到1赫兹。等等。如果您对将来学习更多信号处理感兴趣,请访问维基页面:
Wikipedia - Aliasing
尝试将采样率更改为更高的采样率(标准44.1 kHz),这应该可以解决它!