Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 761
Raffaele Avatar asked May 30 '11 17:05

Raffaele


1 Answers

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();
    }   
}
like image 170
inazaruk Avatar answered Sep 18 '22 22:09

inazaruk