如何通过无限循环改变录音轨的持续时间?

时间:2013-07-02 21:32:04

标签: android audiotrack android-music-player

如何通过无限循环改变录音轨的持续时间?

我知道我必须在audioTrack.play()之前应用以下行:

audioTrack.setLoopPoints (0, generatedSnd.length, -1);

例如,我希望持续时间为半秒,因此,“int”类型的“duration”变量无效。 为此,我希望重复播放声音并使用计时器控制停止的时间。

代码是:

  private int duration = 1; // seconds
    private int sampleRate = 44100; 
    private final int numSamples = duration * sampleRate;
    private final double sample[] = new double[numSamples];
    private double freqOfTone = 261.626; // For example musical note C (Do) is 261.626Hz.
    private final byte generatedSnd[] = new byte[2 * numSamples];

final Thread thread = new Thread(new Runnable() {
                    public void run() {
                        genTone();
                        handler.post(new Runnable() {

                            public void run() {
                                playSound();
                            }
                        });
                    }
                });
                thread.start();
            }
        });


    void genTone() {        
        for (int i = 0; i < numSamples; ++i) {
            sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone));
        }

        // convert to 16 bit pcm sound array
        // assumes the sample buffer is normalised.
        int idx = 0;
        for (final double dVal : sample) {
            // scale to maximum amplitude
            final short val = (short) ((dVal * 32767));
            // 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_STATIC);
        audioTrack.write(generatedSnd, 0, generatedSnd.length);
        audioTrack.play();
    }

2 个答案:

答案 0 :(得分:0)

我认为audioTrack.write(generatedSnd, 0, generatedSnd.length); 0等于所有曲目 你可以编辑文字然后使用: audioTrack.write(generatedSnd, edittext, generatedSnd.length); 然后当用户磁带20在点击播放之前&gt;&gt;玩家将在20秒后循环

答案 1 :(得分:0)

这个对我有用:

audioTrack.setLoopPoints(0,generatedSnd.length / FRAME_SIZE,-1);

如果您正在使用5.1系统,那么帧大小如果是12(6 * 2),或者对于7.1它是16(8 * 2),对于立体声它是4。