Media Player Crashing - android

I am new to programming and upon referring google's dev site I came up with a simple media player that plays the file selected by the user. The app seems to been running fine when choosing the file to be played for the first time but crashes right after selecting a file for the second time. I have pasted the code below. Any help will be appreciated.
public class MainActivity extends Activity {
private static int Reqs =1;
private String a;
MediaPlayer md=new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Start = (Button) findViewById(R.id.button);
final Button Stop = (Button) findViewById(R.id.button3);
final Button Pause = (Button) findViewById(R.id.button2);
final Button Select = (Button) findViewById(R.id.button4);
Pause.setEnabled(false);
Stop.setEnabled(false);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
md.start();
Toast.makeText(getApplicationContext(), "Playing", Toast.LENGTH_SHORT).show();
Pause.setEnabled(true);
Stop.setEnabled(true);
}
});
Stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pause.setEnabled(false);
Toast.makeText(getApplicationContext(), "Stopped", Toast.LENGTH_SHORT).show();
md.stop();
}
});
Pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
md.pause();
Toast.makeText(getApplicationContext(), "Paused", Toast.LENGTH_SHORT).show();
}
});
Select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/mpeg");
startActivityForResult(Intent.createChooser(intent, "Choose"), Reqs);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode <= Reqs && resultCode ==-1) {
Uri videoUri = data.getData();
a = videoUri.toString();
md.setDataSource(a); //try-catch surrounding it
md.prepare(); //try-catch surrounding it
}
}
}

You are not calling reset() to reset the state of the MediaPlayer object.
As the Android's documentation states:
In order to reuse a MediaPlayer object that is in the Error state and recover from the error, reset() can be called to restore the object to its Idle state.
Check it at: https://developer.android.com/reference/android/media/MediaPlayer.html

Related

Having trouble playing audio on the MediaPlayer in Android

New to Android coding here. I'm trying to have the user pick an audio file for the MediaPlayer to play using the "upload" button, and then the MediaPlayer should start playing the file once the user hits "play." Here is my code so far:
public class MainActivity extends Activity {
final int ACTIVITY_CHOOSE_FILE = 1;
File original;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("audio/mpeg");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
});
Button playButton = (Button)findViewById(R.id.playbutton);
playButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(original.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
original = new File(uri.getPath());
String tag = "TAG";
Log.d(tag, original.getAbsolutePath());
}
}
}
}
}
I can choose the audio file fine, but once I hit play nothing happens. What am I doing wrong?
After setting your mediaPlayer data source you have to call mediaPlayer.prepareAsync()
Media Playback in android

Android - How to create MediaPlayer from a user selected song

this is the intent which opens a chooser from the music app
public void launchMusicPlayer(View view) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,1);
}
and below is the onActivityResult code to try and obtain the song
, but the problem is that the test button when pressed, does not play anything
and as i am new to coding i don't know what i am doing wrong.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 1) {
final MediaPlayer testSong = new MediaPlayer();
Uri songUri = data.getData();
try {
testSong.setDataSource(this, songUri);
} catch (IOException e) {
e.printStackTrace();
}
testSong.prepareAsync();
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
testSong.start();
}
});
}
}
The issue maybe because prepareAsync() is asynchronous, so the MediaPlayer may not be ready when you call start(). There are 2 ways to fix this:
Use prepare() instead of prepareAsync()
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
testSong.prepare();
testSong.start();
}
});
call start() method inside setOnPreparedListener()
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
testSong.prepareAsync();
testSong.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
}
});
Refer to the documentation here http://developer.android.com/reference/android/media/MediaPlayer.html

Making Sound Button stop after start

I need a button that will start when pressed and stop when pressed again. Otherwise I have overlapping sounds. Can any of you assist me with the code please? Below is what I currently have and can't get the button to stop when clicked again so currently it is just playing and stops when the sound is done causing sounds to overlap. Getting one to stop when another is pressed would also be ideal but I don't have a clue how to easily incorporate this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boardone);
Button one = (Button) findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(BoardoneActivity.this, R.raw.mouse_laughter);
mp.start();
}
});
Button two = (Button) findViewById(R.id.button2);
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(BoardoneActivity.this, R.raw.evil_laugh);
mp.start();
}
});
Dont use two objects of Media Player. Bleow is the snippet of methods from my project. If any error let me know.
private MediaPlayerManager mRecordingPlayer = null;
private void initAudioPlayer(){
if(mRecordingPlayer == null){
mRecordingPlayer = new MediaPlayerManager();
}
}
private void playMusic(int position){
initAudioPlayer();
mRecordingPlayer.resetPlayer();
mRecordingPlayer.setupPlayback("your reasource");
mRecordingPlayer.startPlaying();
}
private void stopPlaying(){
initAudioPlayer();
if(mRecordingPlayer.isPlaying()){
mRecordingPlayer.pausePlaying();
}
}
#Override
public void onPause() {
clearAudioPlayer();
super.onPause();
}
private void clearAudioPlayer(){
if(mRecordingPlayer != null ){
mRecordingPlayer.resetPlayer();
}
}
#Override
public void onClick(View view) {
boolean on = ((ToggleButton) view).isChecked();
if(on){
playMusic("play music");
((ToggleButton) view).setChecked(true);
}else{
stopPlaying();
}
}
Try it with below code.
mPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
mPlayPause.setText("Play");
}
} else {
if (mp != null) {
mp.start();
mPlayPause.setText("Pause");
}
}
}
});

how do i stop background music when back button is pressed?

i have 2 activities. and 2 different background music plays on both. when i press a button on the first activity it will go to this activity and the changing of music goes smoothly but i want to stop background music when back button is pressed. i tried this but it force closes. is there any other way to do this?
public class Categories extends Activity{
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
mp = MediaPlayer.create(Categories.this, R.raw.looney);
mp.setLooping(true);
mp.start();
Button cartoonButton = (Button) findViewById(R.id.cartoon);
cartoonButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchCartoon = new Intent(Categories.this, Cartoon.class);
startActivity(launchCartoon);
}
});
Button superButton = (Button) findViewById(R.id.hero);
superButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent launchSuperheroes = new Intent(Categories.this, SuperHeroes.class);
startActivity(launchSuperheroes);
}
});
Button singerButton = (Button) findViewById(R.id.singer);
singerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchSinger = new Intent(Categories.this, Singer.class);
startActivity(launchSinger);
}
});
Button famousButton = (Button) findViewById(R.id.famous);
famousButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchFamous = new Intent(Categories.this, Famous.class);
startActivity(launchFamous);
}
});
}
#Override
protected void onResume() {
super.onResume();
mp.start();
}
#Override
protected void onPause() {
super.onPause();
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
You can try this code:
#Override
public void onBackPressed() {
if (player.isPlaying()) {
player.stop();
}
player.release();
super.onBackPressed();
}
Hope this help you :)

Service and background music codes -updated-

i am making a quiz game that has a background music.i saw a very helpful source code using service and background music here http://marakana.com/forums/android/examples/60.html but my problem is i want to add another sound on my EasyOne.class in my correct answer button. what will i add or edit to make it work. my point is. everytime i click the a button of my easyone.class it will play a sound and if i want to turn off all my music even the corrrect button and the background music it will turn off if ill go to my settings.class and click the OFF button. hope you can help me.really appriciate it.
here is my code for my service
public class MusicService extends Service {
private static final String TAG = "";
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "ON", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.bsound);
player.setLooping(false);
}
#Override
public void onDestroy() {
Toast.makeText(this, "OFF", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "ON", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
and here is my for my settings
public class Settings extends Activity implements OnClickListener {
private static final String TAG = "";
Button on, off, back;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
back = (Button) findViewById(R.id.btn_backk);
on = (Button) findViewById(R.id.btn_on);
off = (Button) findViewById(R.id.btn_off);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Back",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainMenu.class);
startActivity(intent);
}
});
on.setOnClickListener(this);
off.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.btn_on:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MusicService.class));
break;
case R.id.btn_off:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MusicService.class));
break;
}
}
}
my EasyOne.class - (class of my level 1 easy mode)
public class EasyOne extends Activity {
ImageButton a, b, c;
Intent intent ;
CountDownTimer cdt;
TextView timer;
MediaPlayer clap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (ImageButton) findViewById(R.id.ib_a);
b = (ImageButton) findViewById(R.id.ib_b);
c = (ImageButton) findViewById(R.id.ib_c);
timer = (TextView) findViewById(R.id.tv_timer);
cdt = new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timer.setText("TIMES UP!");
intent = new Intent(getApplicationContext(),TimesUp.class);
startActivity(intent);
}
};
intent = new Intent(getApplicationContext(),ChoiceTwo.class);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
//i want to add a sound here that will play if they click this button and can turn it OFF on the setting.class OFF button
cdt.cancel();
Intent intent = new Intent(getApplicationContext(),ChoiceTwo.class);
startActivity(intent);
}
});
cdt.start();
}
}
In the main activity of your code (where the game actually starts), put:
startService(new Intent(MusicService.class))
This will start your music playing as soon as the game starts

Categories

Resources