How to change the duration of the audiotrack by an infinite loop?

我是研究僧i 提交于 2019-12-13 06:11:56

问题


How to change the duration of the audiotrack by an infinite loop?

I understand that I must apply the following line before audioTrack.play():

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

For example, I want the duration will be half a second, therefore, the "duration" variable of type "int" isn't valid. To do so I want the sound to play repeatedly and control the time to stop with a Timer.

The code is:

  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();
    }

回答1:


I think audioTrack.write(generatedSnd, 0, generatedSnd.length); 0 equal all track u can but edittext then use : audioTrack.write(generatedSnd, edittext, generatedSnd.length); then when user tape 20 before click play >> the player will loop after 20 second




回答2:


This one worked for me:

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

if you are playing on 5.1 system then frame size if 12 (6*2), or for 7.1 it's 16 (8*2), for stereo it's 4.



来源:https://stackoverflow.com/questions/17436187/how-to-change-the-duration-of-the-audiotrack-by-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!