Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

java - AudioTrack in streaming mode MODE_STREAMING

I need to stream PCM data generated at runtime. So I have a thread with a loop

public void run() {
  while(...) {
    mAudioTrack.write(getPCM(), ...);
  }
}

Unfortunately this doesn't work. It seems it doesn't depend on AudioTrack buffer size. I want it to be very small to simulate sort of low latency behaviour (150 ms) so the user can dinamically change the PCM picked by getPCM()

int bufferSize = 0.150 * sampleRate * channels * bitsPerSample / 8;

However, I tried to increase the buffer size up to 100k with no result

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is short example that works for me:

public class Internal extends Activity
{   
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);              
    }

    public void onPlayClicked(View v)
    {
        start();    
    }

    public void onStopClicked(View v)
    {
        stop();
    }

    boolean m_stop = false;
    AudioTrack m_audioTrack;
    Thread m_noiseThread;

    Runnable m_noiseGenerator = new Runnable()
    {       
        public void run()
        {
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

            /* 8000 bytes per second, 1000 bytes = 125 ms */
            byte [] noiseData = new byte[1000];
            Random rnd = new Random();

            while(!m_stop)
            {           
                rnd.nextBytes(noiseData);   
                m_audioTrack.write(noiseData, 0, noiseData.length);                 
            }
        }
    };

    void start()
    {
        m_stop = false;

        /* 8000 bytes per second*/
        m_audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO,
                                        AudioFormat.ENCODING_PCM_8BIT, 8000 /* 1 second buffer */,
                                        AudioTrack.MODE_STREAM);            

        m_audioTrack.play();        


        m_noiseThread = new Thread(m_noiseGenerator);
        m_noiseThread.start();
    }

    void stop()
    {
        m_stop = true;          
        m_audioTrack.stop();
    }   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...