'Changing audio source for media player (Android Studio)
I am trying to create a button that plays a sound at random from the list of sounds on click. The code I have randomises the first sound, but the subsequent clicks do not trigger any sound. Do I have to release codec after the sound plays?
meow.setOnClickListener((view) ->{
Random random = new Random();
int r = random.nextInt(6-1) + 1;
Toast.makeText(MainActivity.this,Integer.valueOf(r).toString(),Toast.LENGTH_SHORT).show();
try{
if(r==1)
fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat1);
else if (r==2)
fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat2);
else if (r==3)
fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat3);
else if (r==4)
fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat4);
else
fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat5);
mp.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
mp.prepare();
mp.start();
}catch(Exception e){e.printStackTrace();}
});
Solution 1:[1]
you should check state of player, pause/stop if is active and call mp.release();
before loading next song into
with second and further clicks you have probably some Exception
log produced by e.printStackTrace();
, check it out, will tell you what is wrong
also make use of create method, which will load your R.raw
file and return new instance of MediaPlayer
. before doing that release previous player instance if exists
if (mp!=null) mp.release(); // maybe needs also a check if playing and stop before?
mp = MediaPlayer.create(view.getContext(), R.raw.meowcat100);
mp.start(); // dont have to call prepare in this case
Solution 2:[2]
call mp.reset()
before setting new data source
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | m'hd semps |