I have a feature I want to transition over to use Androids AudioTrack
instead of MediaPlayer
, due to a few well known bugs with MediaPlayer
, such as the small gap that appears between looping tracks.
I've been recommended to use AudioTrack
but haven't found to many examples of it in use. I did find a question on SO regarding AudioTrack
and used some of that code to hack together something:
public class TestActivity extends Activity implements Runnable { Button playButton; byte[] byteData = null; int bufSize; AudioTrack myAT = null; Thread playThread = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); playButton = (Button) findViewById(R.id.testButton); InputStream inputStream = getResources().openRawResource(R.raw.whitenoise_wav); try { byteData = new byte[ inputStream.available()]; } catch (IOException e) { e.printStackTrace(); } try { inputStream.read(byteData); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } initialize(); playButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { playThread.start(); } }); } void initialize() { bufSize = android.media.AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT); myAT = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, bufSize, AudioTrack.MODE_STREAM); myAT.setVolume(.2f); playThread = new Thread(this); } public void run() { if (myAT != null) { myAT.play(); myAT.setLoopPoints(0, byteData.length, 6); myAT.write(byteData, 0, byteData.length); } } }
So this does seem to play the entire audio track (~1:00 min) and then stops. Now the end goal here is two have 2 seperate audio tracks playing and looping at the same time. I currently have the audio tracks in the /res/raw/
directory, but I can move them to a simple assets
folder if that would be better. Is my current implementation of AudioTrack
correct? If so, how would I get it to loop?
0 comments:
Post a Comment