I am trying to create a simple Soundboard Android application using ListView items as buttons. (By the way, I'm a beginner programmer)
The idea is that I press a button and a specific sound file is played. If I press any button while playing a sound, it must first stop that sound and then start playing a new one.
At the moment, sounds are played without stopping the sounds currently sounding, so if I spam the buttons, I get several sounds at the same time (and if I click too much at once, the application’s power closes).
I tried using several options:
if (mp.isPlaying()) { mp.stop(); }
But in accordance with what I read in several other sources, I create several instances of the MediaPlayer class, and although they have the same name, the stop () method tries to stop the last mp instance (in some cases not yet created).
I assume my general implementation of the MediaPlayer class is incorrect, but this is the best I could do.
In any case, here is the corresponding code block:
public class soundTest extends Activity { private ListView lv1; private String lv_arr[]={"test 1","test 2","test 3","test 4","test 5"}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lv1=(ListView)findViewById(R.id.ListView01); lv1.setAdapter(new ArrayAdapter<String>(this,R.layout.list_item, lv_arr)); lv1.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view,int position, long id) { if (lv1.getItemAtPosition(position)=="test 1") { MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.sound1); mp.start(); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { mp.release(); } }); } if (lv1.getItemAtPosition(position)=="test 2") { MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.sound2); mp.start(); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { mp.release(); } }); }
Any help would be appreciated, thanks.
Edit (March 22):
I found the following code snippet that should work:
mp.setDataSource(context, Uri.parse("android.resource://" + Config.PACKAGE + "/" + resId));
But I can’t understand how "Config.PACKAGE" works. I just get the error "PACKAGE could not be resolved or is not a field."
I tried replacing “PACKAGE” with the package name, the same error. I also tried:
try { mp.setDataSource(getApplicationContext(),Uri.parse("android.resource://com.mptest/" + R.raw.test2)); } catch (IOException e) { e.printStackTrace(); }
But I can’t work, what exactly to put instead of "//com.mptest/".