1.系統AudioManager類裏面有一個隱藏接口:
可以用反射獲取到系統播放硬件延遲
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
Method m = am.getClass().getMethod("getOutputLatency", int.class);
int latencyMs = (Integer) m.invoke(am, AudioManager.STREAM_MUSIC);
2.系統AudioTrack類裏面也有一個隱藏接口:
if (SDK_INT >= 18) {
Method getLatencyMethod =android.media.AudioTrack.class.getMethod("getLatency", (Class < ? > []) null);
int audioLatencyMs = (int) ((Integer) getLatencyMethod.invoke(audioTrack, (Object[]) null));
}
這個延遲是AudioTrack buffer延遲+系統播放硬件延遲,詳解如下:
AudioTrack延遲底層分析:
uint32_t AudioTrack::latency() const
{
return mLatency;
}
AudioTrack::createTrack函數中對mLatency進行了賦值:
mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
其中afLatency是硬件的延遲。
(1000*mCblk->frameCount) / sampleRate,這一坨,是根據AudioTrack中的audio_track_cblk_t的buffer,計算AudioTrack buffer導致的延遲,也可以在Java層獲取到buffer大小,去計算延遲時間。
afLatency就是AudioManager裏面的getOutputLatency,證據如下 :和getOutputLatency底層實現一致。
uint32_t afLatency;
if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
return NO_INIT;
}