Can't get media player to play mp3 - java

Can anyone tell me why this code doesn't work? It compiles but when I click on the button nothing plays and then it crashes. I'm a noob =[
public class MainActivity extends ActionBarActivity {
private MediaPlayer newTune;
public void playB(View paramView) throws IOException {
newTune = MediaPlayer.create(this, R.raw.b);
if (newTune.isPlaying()) {
// newTune.stop();
} else {
newTune.prepare();
newTune.start();
}
}

There are a couple of problems I can see.
1.) You don't need to call prepare(), as create() has already taken care of this for you.
2.) newTune.isPlaying() is always going to be false, as you've just created a new MediaPlayer.
From the docs:
http://developer.android.com/reference/android/media/MediaPlayer.html
MediaPlayer.onCreate()...
Convenience method to create a MediaPlayer for a given resource id. On
success, prepare() will already have been called and must not be
called again.
Try something like this:
public class MainActivity extends ActionBarActivity {
private MediaPlayer newTune;
public void play() {
newTune = MediaPlayer.create(this, R.raw.b);
newTune.start();
}
}
Here's a simple example of a better way of handling the whole thing:
public class MainActivity extends Activity {
private MediaPlayer mMediaPlayer;
private boolean mIsPrepared;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMediaPlayer = MediaPlayer.create(this, R.raw.raw1);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mIsPrepared = true;
}
});
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playOrPause();
}
});
}
public void playOrPause() {
if (mMediaPlayer == null || !mIsPrepared) {
return;
}
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
} else {
mMediaPlayer.pause();
}
}
}

Related

MediaPlayer.create(this,audio_file)

I am working for the first time in android studio with java. Can anyone please explain the difference between the two codes below.The first one works but the second one doesn't. why??
First Code:
public class MainActivity extends AppCompatActivity {
MediaPlayer player;
public void play(View view) {
player = MediaPlayer.create(this, R.raw.audio_file);
player.start();
}
public void pause(View view) {
player.pause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Second Code:
public class MainActivity extends AppCompatActivity {
MediaPlayer player = MediaPlayer.create(this, R.raw.rain);
public void play(View view) {
player.start();
}
public void pause(View view) {
player.pause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
When MediaPlayer is declared global but created in a method.
So when you declare MediaPlayer in global but don't initialize it, Then it's just a reference Variable.
While doing this MediaPlayer is not ready, So when is it Ready?
public void play(View view) {
player = MediaPlayer.create(this, R.raw.audio_file); // <-- when you initialize it.
player.start();
}
When ever we use .create it sets the MediaPlayer in prepared State, (if the creation using create method is successful.)
Declaring and initializing MediaPlayer in Global.
When you write this:
public class MainActivity extends AppCompatActivity {
MediaPlayer player = MediaPlayer.create(this, R.raw.rain);
}
it means the media player is set to prepared state in start, There would be cases where you dont want your player to just use your resources. While doing this declaring and initializing it globally, it's using your resources when you don't need them.
While in previous example you just had made a Reference to the MediaPlayer But used it when ever you call play()
Usually in java the best way to initialze a variable is inside the contractor of the class like this :
public class MainActivity extends AppCompatActivity {
MediaPlayer player;
public MainActivity() {
this.player = MediaPlayer.create(this, R.raw.audio_file);
}
public void play(View view) {
player.start();
}
public void pause(View view) {
player.pause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}}
The second code propably isn't working because when you initialize the variable outside the constractor or outside of some function the current class haven't been completely intialized yet and you pass as a variable the current class with the code "this"

Music player with Seekbar (Android Studio)

I was working in a very simple music player with a seek bar. But I got a problem with playing music,it doesn't work correctly every second - it backwards a while, then remain again like it's a buggy.
I know why but I can't solve it.
When the progress bar moves forward, the music recalibrates and vice versa, when the music moves forward, the progress bar recalibrates.
It's probably because of that that every time it goes back.
But I tried several things and still have the same problem.
Another problem is that when the music is paused, the progress bar goes in the opposite direction until it reaches zero. It doesn't stay where it was before the break.
The full code :
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SeekBar seekBar;
private boolean bool = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.seekBar = (SeekBar) findViewById(R.id.sound_bar);
this.mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition() * seekBar.getMax() / mediaPlayer.getDuration());
}
}, 500, 500);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mediaPlayer.seekTo(seekBar.getProgress() * mediaPlayer.getDuration() / seekBar.getMax());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public void playSound(View view) {
Button button = (Button) view;
if(bool) {
mediaPlayer.pause();
bool = false;
button.setText("Jouer le son");
} else {
mediaPlayer.start();
bool = true;
button.setText("Mettre en pause");
}
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onStart() {
super.onStart();
if(bool) {
mediaPlayer.start();
}
}
}
Maybe use another thread to control the seekbar would help.
Take a look at this

How to terminate music using back button of phone and created back button?

I was having some bugs with playing a music in my app. It wont stop playing even if I exit the app. It will only stop if I hit pause or terminate the app. Here's my code for music. What should I do code to stop it.
public void play_brain(View g){
final MediaPlayer brainMP = new MediaPlayer();
try {
brainMP.setDataSource("https://firebasestorage.googleapis.com/v0/b/capstone-katugna-001.appspot.com/o/meditation%20music%201%20minute%20peaceful%20music%201%20minute%20mindfulness%20meditation%201%20minute%20relax%20music%201.mp3?alt=media&token=f34fe7c7-54f1-4645-88cf-5e7a21f401d8");
brainMP.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
brainMP.prepare();
} catch (IOException e) {
e.printStackTrace();
}
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
brainMP.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.pause();
}
});
brainMP.pause();
}
});
}
You can try using this code:
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private Button buttonStartPause;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// Initialize your MediaPlayer object here
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
}
buttonStartPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
// here you can set the play icon to your button
} else {
mediaplayer.start();
// here you can set the pause icon to your button
}
}
});
// To capture back button's pression you can override onBackPressed() in your Activity:
#Override
public void onBackPressed() {
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
}
super.onBackPressed();
}
}

How to pause/stop music when home or back button is pressed?

Here is my code. I'm very new to Java and I know that this question is already been posted but still I didn't get the expected outpost so I had to post.
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer policeSound = MediaPlayer.create(this, R.raw.police);
Button policeSounds = (Button) this.findViewById(R.id.police);
policeSounds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (policeSound.isPlaying()){
policeSound.stop();
}
else {
policeSound.start();
}
}
});
}
}
I tried adding onBackPressed() code to this but it couldn't detect the 'policeSound' as it was detected in the previous method!
And someone please even teach me how to use #Override annotations!
To detect the 'policeSound' in other methods you need to make it be a field of a class:
private MediaPlayer policeSound;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
policeSound = MediaPlayer.create(this, R.raw.police);
Button policeSounds = (Button) this.findViewById(R.id.police);
policeSounds.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (policeSound.isPlaying()) {
policeSound.stop();
} else {
policeSound.start();
}
}
}
);
}
In your codes policeSound is a local variable which is be seen only in Oncreate() method,as Oleh Sokolov said, you should declare policeSound as a field of class.
About #Override , you could see this good explanation
and in android studio , when you press ctrl + o in java class file, you can override superclass method, and IDE will add #Override automatically for you.

how can I use MediaPlayer outside my mainActivity in android (how to call it from mainActivity)

IM trying to create a simple app and for it I have to have a mediaPlayer not in the mainActivity. how can I do this?(in what kind of class does it need to be and how to write the method and instance it in main).
Im quite new to android and have nooo idea how to do this(its probably very simple...)
any help would be great. thanks ahead!
You can create such a class for usage in every Activity:
public class MediaPlayerUtil {
public static void playSound(Context context, int soundFileResId) {
MediaPlayer mp = MediaPlayer.create(context, soundFileResId);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
mp=null;
}
});
mp.start();
}
}
Then inside any Activity just call MediaPlayerUtil.playSound(this, R.raw.your_sound_file) where this will be a reference to your activity and by R.raw.your_sound_file you reference file in /res/raw directory of your project.
This is an example of a simple app like to ask just have to create the folder raw, where the audio was located.
mysong replace the file with the name of your audio
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button play, stop;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button)findViewById(R.id. play);
stop = (Button)findViewById(R.id.stop);
play.setOnClickListener(this);
stop.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.play:
play();
break;
case R.id.stop:
stop();
break;
}
}
private void play (){
destruir();
mp = MediaPlayer.create(this, R.raw.mysong);
mp.start();
}
private void stop(){
mp.stop();
}
private void destruir(){
if (mp !=null)
mp.release();
}
}

Categories