在Android AudioTrack中使用缓冲区 [英] Using a buffer with Android AudioTrack

查看:97
本文介绍了在Android AudioTrack中使用缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在 AudioTrack 中使用缓冲区有效地流音乐.我知道您可以使用 write 方法,但是一旦音频排队,您如何知道还剩多少与已使用/播放了多少呢?抱歉,这是一个基本问题.我了解缓冲区的概念,但不确定如何编写缓冲区,尤其是使用AudioTrack.

I'm trying to figure how I would use a buffer with AudioTrack to effectively stream music. I know you can queue audio using the write method but once the audio is queued how do you tell how much is left vs. how much has been used/played? Sorry if this is a rudimentary question. I understand the concept of a buffer I'm just not sure how to write one, especially using AudioTrack.

推荐答案

AudioTrack.write() returns "number of bytes written" as an int, and you specify the number of bytes in the buffer when constructing the AudioTrack.

因此,要跟踪剩余的缓冲区空间,可以保留一个累加器变量,以便知道总共写入了多少字节,并在每次调用

Therefore, to track how much buffer space remains, you could keep an accumulator variable so you know how many bytes have been written in total, and set this variable to zero whenever you call AudioTrack.flush(). However, the linked documentation states "it is typical to use chunks of 1/2 of the total size to permit double-buffering", so it might be simple enough to simply remember if you've written zero, once or twice since calling flush.

要知道已播放了多少缓冲区,请使用 AudioTrack.getPlaybackHeadPosition()返回当前缓冲区播放的的数量(即在停止,刷新或重新加载时重置为零)带符号的32位整数,但将其解释为无符号的32位整数.这实际上意味着您将其分配给一个int,如下所示.

To tell how much of the buffer has been played, use AudioTrack.getPlaybackHeadPosition() which returns the number of frames that have been played of the current buffer (i.e. reset to zero on stop, flush or reload) as signed 32-bit integer but to be interpreted as an unsigned 32-bit integer. All this really means is that you assign it to an int as follows.

int bufferPlaybackFrame = myAudioTrack.getPlaybackHeadPosition() & 0xFF;

您可以认为帧等同于样本.即,您可以从用于构造AudioTrack的AudioFormat算出每个样本正在使用多少位(因此是字节).

You can think of frames as equivalent to samples. i.e. You can work out from the AudioFormat used to construct the AudioTrack how many bits (and hence bytes) are being used per sample.

最后,万一有人想知道,您将永远无法分辨出有多少源文件或流可以通过该对象播放(一个原因是它被设计为可与永久性24/7流一起使用,没有结尾),因此,如果您要像在某些视频播放网站上看到的那样进行计算,它会暂停视频流,直到缓冲了足够的ID才能以您当前的下载速率观看整个视频,您必须在某些地方传递该信息另一种方式.

Finally, in case someone was wondering, you'll never be able to tell how much of the source file or stream is left to play through this object (one reason being it's designed to work with permanent 24/7 streams, with no ending), so if you wanted to make a calculation like you see on some video playing websites, that pause the stream until enough id buffered to see the whole video at your current download rate, you'll have to pass that information in some other way.

这篇关于在Android AudioTrack中使用缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆