我正在使用AudioTrack播放一系列正弦波,但是当我在HTC M9上运行它时,它只播放部分样本,并且它将播放多长时间是随机的.即G.我有20种音调可以播放,但它只有2到17.5种音调.是的,它甚至会在音调中间停止.
这是我的代码,来自另一个答案:
ArrayList<double[]> samples = new ArrayList<>(); int numSamples = 0; for (final ToneSegment seg : sequence) { int num = seg.getDuration() * sampleRate / 1000; double[] sample = new double[num]; for (int i = 0; i < num; ++i) { sample[i] = Math.sin(2 * Math.PI * i * seg.getPitch() / sampleRate); } samples.add(sample); numSamples += num; } byte generatedSnd[] = new byte[2 * numSamples]; int idx = 0; for (double[] sample : samples) { for (final double dVal : sample) { final short val = (short) ((dVal * 32767)); generatedSnd[idx++] = (byte) (val & 0x00ff); generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8); } } audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRate,AudioFormat.CHANNEL_OUT_MONO,AudioFormat.ENCODING_PCM_16BIT,generatedSnd.length,AudioTrack.MODE_STATIC); audioTrack.write(generatedSnd,generatedSnd.length); audioTrack.play();
有谁有想法吗?谢谢!
解决方法
您正在使用AudioTrack.MODE_STATIC,用于短音和低延迟要求,同时您应该使用AudioTrack.MODE_STREAM. AudioTrack.MODE_STREAM适用于较长的流,但我不知道你的样本有多长.所以你可以尝试改变AudioTrack:
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,AudioTrack.MODE_STREAM);
此外,AudioTrack需要以字节为单位的缓冲区大小,短路需要乘以2来计算正确的所需字节数.你可以像这样破解它:
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,generatedSnd.length*2,AudioTrack.MODE_STREAM);