What is currently happening with my Android app:
I matched a simple image with a button and started the sound on click. In each click, I create a MediaPlayer object with a sound file in my source folder, I set OnClickListener for this MediaPlayer object, which stops playing the file and frees it, and then I play the MediaPlayer object.
Code for a specific section:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); ImageButton start = (ImageButton) findViewById(R.id.imageButton1); start.setOnClickListener(new OnClickListener() { public void onClick(View v) { MediaPlayer play = MediaPlayer.create(MainActivity.this, R.raw.dvno); play.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { mp.stop(); mp.release(); mp = null; } }); play.start(); } }); }
What is wrong with him:
It works fine and does not crash, but it is terrible for memory and very slow in general. I would like users to press the button as many times in a row as possible, and hear the sound game instantly again and again with overlapping. Creating a new MediaPlayer object on every click and waiting for it to complete and release will consume too many resources, and the sound often lags behind the actual click of a button. I would like to be able to create one sound as a MediaPlayer object that can be played back when it matches itself.
Possible Solution:
Create a single MediaPlayer target in the onCreate area, not onClick, and somehow use the threads to launch the MediaPlayer every time you click. I read that this might be a possible solution, but I have never used streams before, and I donβt know if they are slower than my current code, so I would like to know if there are no streams that can be simpler. Manipulating the state of one MediaPlayer to overlap on itself seems impossible at the moment, but maybe I'm wrong.
Can this really lead to a program crash due to illegal conditions? If not, will it be slower than I want? And if not, can someone suggest a fix for my code?
source share