Android AudioTrack() How do you stop a playing stream after it starts
My target API is 2.2 I create audio snippets on the fly so using soundpool or mediaplayer are out of the question. One item I found that wasnt/isnt well documented is that AudioTrack() will create a set limit of instances. I found it to very between 6 and 12 instances. One thing that was not covered in the docs is that each time initiate a AudioTrack() it creates a new instance. Session ID is not implemented until version 2.3 so GetSessionID() is not available under 2.2. A lot of problems I see with questions about are that each time you do AudioTrack audioTrack = (new) AudioTrack (the various params here); It starts a new process so just doing audioTrack.stop(); Does not work if you are trying to stop a previous stream.
SO my problem is I start an audioTrack playing that may be over minute long. This is done in out of stream process (uh separate routine being passed the parameters) the streams play fine. The program is doing some other user directed task and I want to stop the the audiotrack before it completes its' playback buffer.
I开发者_开发百科 need a way of referencing the audio track that is playing and stopping it. My newbieness and too long a C programmer along with the lack of Java experience is getting in the way. Surely there must be a way to stop audiotrack at any time. Looking for just a way to reference the audiotrack and stop it.
I thought maybe android.media.audiotrack.stop(); might be close but close dont cut it. Help! I've spent 15 hours looking for an example. TnxCalling these 3 methods worked for me. I also have code to stop the buffering which is in another thread.
audioTrack.flush();
audioTrack.stop();
audioTrack.release();
Indeed, stop()
will not cut the playback right away. What you need is pause()
+ flush()
. As per documentation:
public void stop ()
Stops playing the audio data. When used on an instance created in MODE_STREAM mode, audio will stop playing after the last buffer that was written has been played. For an immediate stop, use pause(), followed by flush() to discard audio data that hasn't been played back yet.
Calling pause by itself cuts the playback quite fast. However, I noticed that sometimes, the pause + flush sequence will continue reading the buffer for a while. Introducing some delay between the pause()
and flush()
calls solved this problem in my application.
Unless I am missing something, whenever you create a new instance of an AudioTrack make sure and keep it around (array, linked list, hashmap, etc). That way at any point you can go back to a previously create object and call its methods.
精彩评论