I have a problem with pausing a MediaPlayer. When I play it, and click the pause button it's working, but when it's playing longer than 10 seconds it's not pausing.
Here is my code:
private TextView tvState;
private MediaPlayer mediaPlayer = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_player);
ImageButton btnPlay = (ImageButton) findViewById(R.id.btnPlay);
ImageButton btnPause = (ImageButton) findViewById(R.id.btnPause);
TextView tvAuthor = (TextView) findViewById(R.id.tvAuthor);
TextView tvSong = (TextView) findViewById(R.id.tvSong);
tvState = (TextView) findViewById(R.id.tvState);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String json = bundle.getString("songModel");
final SongModel songModel = new Gson().fromJson(json, SongModel.class);
tvAuthor.setText(songModel.getAuthor());
tvSong.setText(songModel.getName());
PrepareMediaPlayer(songModel);
}
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
} else if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
if (mediaPlayer.isPlaying()) {
tvState.setText("Played");
}
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
if (!mediaPlayer.isPlaying()) {
tvState.setText("Paused");
}
}
});
}
public void PrepareMediaPlayer(SongModel song) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(song.getLink());
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying()) {
mp.start();
}
}
});
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
});
}
My OS: Android 4.0.4, API 15
Related
**Main Activity.java**
This is main activity where I instantiate all methods/objects. Here I use Dexter library to grab files from user's external storage, then I made one method called find songs which helps in finding the path of files and list them accordingly. Then I made another method called display songs which will help in getting the whole size of songs and then display the whole list with their names accordingly. Then with the help of custom adapter I passed my list of songs which is in array named item.
public class MainActivity extends AppCompatActivity {
ListView listView;
String [] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission(){
Dexter.withContext(this)
.withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest
.permissi
on.RECORD_AUDIO)
.withListener(new MultiplePermissionsListener() {
#RequiresApi(api = Build.VERSION_CODES.R)
#Override
public void
onPermissionsChecked(MultiplePermissionsReport
multiplePermissionsReport)
{
displaySongs();
}
#Override
public void
onPermissionRationaleShouldBeShown(List<PermissionRequest> list,
PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file){
ArrayList arrayList = new ArrayList();
Log.d(TAG, "findSong:"+ file.getPath());
File [] files = file.listFiles();
if (files!=null) {
Log.d(TAG, "findSong:"+ files.length);
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
arrayList.addAll(findSong(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") &&
!singleFile.getName().startsWith(".")) {
arrayList.add(singleFile);
}
}
}
}
return arrayList;
}
public void displaySongs(){
ArrayList<File> mySongs =
findSong(Environment.getExternalStorageDirectory());
String [] items = new String [mySongs.size()];
if(mySongs == null)return; // this is very important function
otherwise app will crash
for (int i=0; i<mySongs.size(); i++){
items[i] = mySongs.get(i).getName().replace(".mp3",
"");
}
Log.d(TAG, "displaySongs:"+ items.length);
(this,
android.R.layout.simple_list_item_1,items);
CustomAdapter customAdapter = new CustomAdapter(this,
Arrays.asList(items));
Log.d(TAG, "displaySongs:"+ customAdapter.getCount());
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
String currentSong = (String)
listView.getItemAtPosition(position);
startActivity(new Intent(getApplicationContext(),
PlayerActivity.class)
.putExtra("currentSong", currentSong)
.putExtra("position",position)
.putExtra("songs",mySongs));
}
});
}
class CustomAdapter extends ArrayAdapter {
public android.util.Log Log;
List<String> names;
LayoutInflater inflater;
Context context;
public CustomAdapter(Context context, List<String> names) {
super(context,R.layout.list_item ,names);
this.names=names;
this.context=context;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
inflater=LayoutInflater.from(getContext()); //inflater is
responsible for taking your xml files that defines your layout
// and converting them into view objects.
View
customview=inflater.inflate(R.layout.list_item,parent,false);
String data=names.get(position);
//String data1=names.get(position+1);
TextView tv=
(TextView)customview.findViewById(R.id.textsongname);
tv.setText(data);
tv.setSelected(true);
//TextView tv1=(TextView)customview.findViewById(R.id.TeamB);
//tv1.setText(data1);
return customview;
}
}
}
**PlayerActivity.java**
I tried to make a Thread named update seek bar which will update my seek bar to current position after that I applied set on click bar change listener so that whenever user update position of sidebar it should get updated. But error here is that when I run my app using this code on emulator its working completely fine but when installed in my phone 2 errors are coming. One after completion of song its not jumping automatically to the next song and second when user update sidebar and press next, sidebar is not coming to position 0, and this whole error is showing on my phone not in emulator.
public class PlayerActivity extends AppCompatActivity {
Button play,next,fastforward, previous, fastrewind;
TextView txtsn, txtsstart, txtsstop;
SeekBar seekBar;
BarVisualizer visualizer;
Thread updateSeekBar;
String sName;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList mySongs;
ImageView imageView;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()== android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
if (visualizer != null){
visualizer.release();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setTitle("Now Playing");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
play = findViewById(R.id.play);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
fastforward = findViewById(R.id.fastforward);
fastrewind = findViewById(R.id.fastrewind);
txtsn = findViewById(R.id.txtsn);
txtsstart = findViewById(R.id.txtsstart);
txtsstop = findViewById(R.id.txtsstop);
seekBar = findViewById(R.id.seekbar);
visualizer = findViewById(R.id.blast);
imageView = findViewById(R.id.iamgeView);
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
}
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
mySongs = (ArrayList) bundle.getParcelableArrayList("songs");
sName = intent.getStringExtra("currentSong");
position = bundle.getInt("position",0);
txtsn.setText(sName);
txtsn.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString()); // uri is
usually use tell a content provider what we want to access by
reference
mediaPlayer = MediaPlayer.create(this,uri);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
updateSeekBar = new Thread(){
#Override
public void run() {
int currentPosition = 0;
while (currentPosition<mediaPlayer.getDuration()){
try {
currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
sleep(500);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
};
updateSeekBar.start();
seekBar.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
String endTime = createTime(mediaPlayer.getDuration());
txtsstop.setText(endTime);
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime =
createTime(mediaPlayer.getCurrentPosition());
txtsstart.setText(currentTime);
handler.postDelayed(this,delay);
}
},delay);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
play.setBackgroundResource(R.drawable.ic_play);
mediaPlayer.pause();
}
else {
play.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=mySongs.size()-1){
position = position + 1;
}
else{
position = 0;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
mediaPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
next.performClick();
}
});
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=0){
position = position - 1;
}
else{
position = mySongs.size() - 1;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
fastforward.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()+1000);
}
}
});
fastrewind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()-1000);
}
}
});
}
private boolean isPermissionGranted(){
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
}
else {
int readExternalStoragePermission =
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
return readExternalStoragePermission ==
PackageManager.PERMISSION_GRANTED;
}
}
public void startAnimation(View view){
ObjectAnimator animator =
ObjectAnimator.ofFloat(imageView,"rotation",0f,360f);
animator.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(animator);
animatorSet.start();
}
public String createTime(int duration) {
String time = "";
int min = duration/1000/60;
int sec = duration/1000%60;
time+=min+":";
if (sec<10) {
time+="0";
}
time+=sec;
return time;
}
}
https://www.youtube.com/watch?v=aD0WWoVDl0I
I have tried this code. Does nothing
My present code is this answer's
https://stackoverflow.com/a/6312631/10903899
Code
public class Radio2 extends Fragment {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_radio2, container, false);
playSeekBar = (ProgressBar) rootView.findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) rootView.findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
buttonStopPlay = (Button) rootView.findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
initializeMediaPlayer();
return rootView;
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://usa8-vn.mixstream.net:8138");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
public void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
The worst part is that the stacktrace is empty, which means that im not getting any error in the catch blocks. The code inside the try block is executing. But nothing happens. I even tried changing the URL but nothing.
Actually i have 2 activities , in the main activity i am displaying all the songs using recycler view and setup an onClickListner on it, and when someone taps on it , it launches a new activity(MediaPlayer Activity) and start playing the song along with media controls like (paly, pause and seekBar).
But when i get back to the main activity and click on a button (which basically takes to the MediaPlayer activity again) all the mediaPlayer and seekBar progress are gone also the (play, pause, next and previous buttons) are not responding to the clicks.
This is from where i am starting the MediaPlayer activity :
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.Song.setText(mData.get(position).title);
holder.Artist.setText(mData.get(position).artist);
Glide.with(mcontext).load(mData.get(position).imagePath).
placeholder(R.drawable.unknown_art).into(holder.PhotoId);
holder.Options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mcontext, "You clicked on options", Toast.LENGTH_SHORT).show();
}
});
holder.RL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mcontext, MediaPlayerActivity.class);
intent.putExtra("songPosition",position);
mcontext.startActivity(intent);
}
});
These are the codes in the MediaPlayerActivity :
public class MediaPlayerActivity extends AppCompatActivity {
static MediaPlayer mediaPlayer=null;
static int pos=0;
SeekBar seekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Intent intent = getIntent();
pos = intent.getIntExtra("songPosition",pos);
seekBar = (SeekBar)findViewById(R.id.seekBar);
Button next = (Button)findViewById(R.id.button_1);
Button previous = (Button)findViewById(R.id.button_2);
final Button play_pause = (Button)findViewById(R.id.button_3);
final TextView info = (TextView)findViewById(R.id.songInfo);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
playMedia(pos);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
playMedia(++pos);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this,"Already the last song!!!",Toast.LENGTH_SHORT).show();
}
}
});
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
playMedia(--pos);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this,"Already the first song!!!",Toast.LENGTH_SHORT).show();
}
}
});
play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
play_pause.setText(R.string.mp_play);
mediaPlayer.pause();
}
else{
play_pause.setText(R.string.mp_Pause);
mediaPlayer.start();
}
}
});
}
public void playMedia(int pos){
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(VerticalRecyclerViewAdapter.mData.get(pos).songPath);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
mediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
setSeekbarProgress();
onSeekbarChange();
playNext();
}
public void playNext(){
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
try {
mediaPlayer.release();
playMedia(++MediaPlayerActivity.pos);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this, "Already the last song", Toast.LENGTH_SHORT).show();
}
}
});
}
public void setSeekbarProgress(){
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
if (mediaPlayer != null) {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
}
catch (RuntimeException e){
Log.i("CRASH",""+e.getMessage());
}
}
},0,1000);
}
public void onSeekbarChange(){
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(b) {
mediaPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
And this is where from i wanted to go back to the MediaPlayer Activity (on button click ) :
mFloatingToolbar.setClickListener(new FloatingToolbar.ItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.music:
Intent intent = new Intent(getActivity(),MediaPlayerActivity.class);
startActivity(intent);
break;
case R.id.pause :
break;
case R.id.next :
Toast.makeText(getContext(), "Next", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getContext(), "Back", Toast.LENGTH_SHORT).show();
verticalRecyclerViewAdapter.notifyDataSetChanged();
break;
}
}
#Override
public void onItemLongClick(MenuItem item) {
}
});
I have song which duration is 15min. But I would like to play this song for 30 minutes. Also when the user will download PRO version of the application, the song should play for 2 hours. How can I set the time?
I am new to Java and Android.
Thanks for your help.
public class MainActivity extends Activity {
Button start, stop;
// Button btn_play, btn_stop, btn_pause;
MediaPlayer mp;
TextView display, comment;
int length;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
length = 0;
start = (Button) findViewById(R.id.bStart);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.splahsound);
mp.seekTo(length);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
mp.release(); // free up memory
mp = null;
length = 0;
}
});
}
});
stop = (Button) findViewById(R.id.bDur);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
try {
mp.stop();
mp.reset();
mp.release();
mp = null;
length = 0;
} catch (Exception e) {
Log.d("error", e.toString());
}
}
}
});
}
}
Use TimerTask. A similar question has already been answered here, so pointing to that.
When a sound that the user previously selected is playing, how can I stop that sound and immediately play the new selected sound? The code I have so far only stops the new sound, but the user has to select the sound again in order to play it.
public class MainActivity extends Activity {
public MediaPlayer mediaPlayer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a = (Button) findViewById(R.id.First);
a.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.firstsound);
mediaPlayer.stop();
}
else {
mediaPlayer.start();
mediaPlayer = null;
}
}
}
);
Button b = (Button) findViewById(R.id.Second);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.secondsound);
mediaPlayer.stop();
}
else {
mediaPlayer.start();
mediaPlayer = null;
}
}
}
);
I am making a soundboard with over 30 sounds, if that helps at all. What (slight I assume) changes would I need to make to my code? Any help would be greatly appreciated!
public class MainActivity extends Activity {
public MediaPlayer mediaPlayer = null;
public Boolean playing=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a = (Button) findViewById(R.id.First);
a.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
(playing)mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.firstsound);
mediaPlayer.start();
playing=true;
}
});
Button b = (Button) findViewById(R.id.Second);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
(playing)mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.firstsound);
mediaPlayer.start();
playing=true;
}
});
}
}