MediaPlayer.create(this,audio_file) - java

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"

Related

why I can not use create method out side a function in AppCompatActivity

My app is crashing when I launch when I write code like this
public class MainActivity extends AppCompatActivity {
MediaPlayer mplayer= MediaPlayer.create(this,R.raw.song);
public void playMusic(View view){
mplayer.start();
}
public void pauseMusic(View view){
mplayer.pause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
but when I write above code like this then it's working perfectly fine
public class MainActivity extends AppCompatActivity {
MediaPlayer mplayer;
public void playMusic(View view){
mplayer= MediaPlayer.create(this,R.raw.song);
mplayer.start();
}
public void pauseMusic(View view){
mplayer.pause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
please anybody tell me what is wrong with first code
Thanks
because the player must be initialized at the moment when the context is not empty. That is, in the upper code, context == null in player. Therefore, the application crashes.

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.

Calling a method of MainActivity from other class

I am developing an Android app and thus, I have a MainActivity class. Inside of that MainActivity class, I have a method, let's call it doSomething():
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doSomething(){
// bla bla bla
}
}
I also have a different class (with different layout) that is called OtherActivity. I want to use the doSomething method inside it:
public class OtherActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity_layout);
// Let's use doSomething()
}
}
I tried this:
public class OtherActivity extends AppCompatActivity {
MainActivity main;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity_layout);
// Let's use doSomething()
MainActivity main = new MainActivity();
main.doSomething();
}
}
But it does not work. I also tried to make OtherActivity to extend the MainActivity, doing the following:
public class OtherActivity extends MainActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity_layout);
// Let's use doSomething()
super.doSomething();
}
}
But it does not allow me to initialize the layout...
How can I do?
Thanks in advance.
To communicate between to Activity Broadcast is the best way, and for the same application, we can use local broadcast using LocalBroadcastManager.
First, we should register one broadcast in MainActivity,
public class MainActivity1 extends AppCompatActivity {
public static final String INTENT_FILTER = "do_some_action";
public static final String INTENT_BUNDLE_VALUE = "value1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
LocalBroadcastManager.getInstance(this).registerReceiver(
mChangeListener, new IntentFilter(INTENT_FILTER));
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mChangeListener);
}
private BroadcastReceiver mChangeListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intentData) {
// you can do anything here
if (intentData != null && intentData.hasExtra(INTENT_BUNDLE_VALUE)) {
String value = intentData.getStringExtra(INTENT_BUNDLE_VALUE);
doSomeAction(value);
}
}
};
private void doSomeAction(String value) {
}
}
Then to do some action in MainActivity from OtherActivity, we can send Local broadcast from OtherActivity it will reach the receiver of Which we register in MainActivity,
public class OtherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
// You can call MainActivity to do some actions
Intent intent = new Intent(MainActivity1.INTENT_FILTER);
intent.putExtra(MainActivity1.INTENT_BUNDLE_VALUE, "Any string or any value");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
Done!!!.
Something like this should do the trick, I'm going to make a static navigator to handle your navigation logic. If you are opposed to static methods you could also make them on your Application object to make it easier to manage dependencies, I'm just making it static for simplicity.
//Making this fully static for simplicity, this is fine for a small app
//you can make it a singleton on the application class for more flexibility
public class Navigator {
//static member vars that determine navigation
// pass in Context if needed for navigation purposes
public static void doSomething(Context context){
// bla bla bla
}
}
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
}
private void doSomething() {
Navigator.doSomething(this);
}
}
public class OtherActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity_layout);
}
private void doSomething() {
Navigator.doSomething(this);
}
}

Can't get media player to play mp3

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();
}
}
}

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