java 流媒体模式下的 AudioTrack MODE_STREAMING

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6179392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:43:09  来源:igfitidea点击:

AudioTrack in streaming mode MODE_STREAMING

javaandroidaudio

提问by Raffaele

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

我需要流式传输在运行时生成的 PCM 数据。所以我有一个带循环的线程

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

不幸的是,这不起作用。似乎它不依赖于 AudioTrack 缓冲区大小。我希望它非常小以模拟低延迟行为(150 毫秒),以便用户可以动态更改 getPCM() 选择的 PCM

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

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

但是,我尝试将缓冲区大小增加到 100k,但没有结果

回答by inazaruk

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