NullPointerException in Java Android App MediaPlayer - java

HELP please this is just a simple android app I am developing, it's meant to play a sound every time you click the button....it works when I click the button at a slow pace, but always crashes if I click the button at a fast pace due to a runtime error - NullPointerException!.....I don't know what I am doing wrong.
THIS IS MY CODE
public class Main extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button e = (Button) findViewById(R.id.Button1);
e.setOnClickListener(this);
}
public void onClick(View v){
if(v.getId()==R.id.imageButton1){
final MediaPlayer i = MediaPlayer.create(Main.this, R.raw.sound);
i.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
i.release();
}
});
i.start();
}
}
}

Its only a guess but in the documentation here you will find the following
public static MediaPlayer create (Context context, int resid)
...
Returns a MediaPlayer object, or null if creation failed
This means you should make sure that the line
final MediaPlayer i = MediaPlayer.create(Main.this, R.raw.sound);
does not return a null.
Edit:
Im really not sure how to handle the situation if create(Context context, int resid) is failing. But you have to do, because it is even from the documentation very clear that it can happen.
To be sure this is really the problem just ignore this case and return from your handler.
For example...
public void onClick(View v)
{
if(v.getId() == R.id.imageButton1)
{
final MediaPlayer i = MediaPlayer.create(Main.this, R.raw.sound);
if (i != null)
{
...
i.start();
}
}
}

Try it this way....
public class Blah extends Activity implements OnClickListener {
MediaPlayer mp;
#Override
public void onCreate(Bundle b)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button e = (Button) findViewById(R.id.Button1);
mp = MediaPlayer.create(R.raw.match);
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
i.release();
}
});
e.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp.seekTo(0);
mp.start();
}
});
}
}

I had the same problem
my solution was to re-encode the mp3 files with the LAME mp3 encoder
You can use this program: http://www.freac.org/index.php/en/downloads-mainmenu-33
apparently android is quite picky about mp3 codecs

Related

Why doesn't my song work in my android app?

My audio doesn't play.
What is the problem ??
public class AudioActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
final MediaPlayer mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
Button play = (Button) findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
mp.start();
}
});
Button bause = (Button) findViewById(R.id.bause);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
mp.pause();
}
});
}
}
You called setOnClickListener() on the play button twice. You meant to call bause.setOnClickListener(). When you hit the play button, instead it is pausing.
You are setting OnClickListener of play button twice.
So when you click the play button it will pause the media player instead of playing it.
change it to following:
Button bause = (Button) findViewById(R.id.bause);
bause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
mp.pause();
}
});
This has to do with method scopes. You're creating the MediaPlayer instance inside the onCreate method. When that method ends, the mp variable goes away as well since it was created in the method's scope. When the onClickListener is executed, the variable doesn't exist anymore. Move the variable declaration to the class' scope, so that it remains available for the lifetime of the class. Something like:
public class AudioActivity extends AppCompatActivity {
private MediaPlayer mp;
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
//...
}

How to stop playing sounds on button click to start another sound file?

I have two buttons and two songs. If I click the first button, the first sound plays. But if I click the second button while the first sound is playing the second sound starts playing too.
How can I stop other sounds?
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer johnCenaPlayer = MediaPlayer.create(this, R.raw.john_cena);
Button johnCenaButton = (Button) findViewById(R.id.john_cena_button);
johnCenaButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
johnCenaPlayer.start();
}
});
final MediaPlayer haGayPlayer = MediaPlayer.create(this, R.id.ha_gay_button);
Button haGayButton = (Button) findViewById(R.id.ha_gay_button);
haGayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
haGayPlayer.start();
}
});
}
Stop the other MediaPlayer in clickListener using stop() method.
public void onClick(View view) {
ha_gay.stop()
john_cena.start();
}
If you have many audio files use a single MediaPlayer and change the sources dynamically.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mediaPlayer = new MediaPlayer();
Button john_cena_button = (Button) findViewById(R.id.john_cena_button);
john_cena_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopAndPlay(R.raw.john_cena, mediaPlayer);
}
});
Button ha_gay_button = (Button) findViewById(R.id.ha_gay_button);
ha_gay_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopAndPlay(R.raw.ha_gay, mediaPlayer);
}
});
}
// This resets the mediaPlayer and starts the given audio
private void stopAndPlay(int rawId, MediaPlayer mediaPlayer) {
mediaPlayer.reset();
AssetFileDescriptor afd = this.getResources().openRawResourceFd(rawId);
try {
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
Try this one. Do it same for the other.
final MediaPlayer john_cena = MediaPlayer.create(this, R.raw.john_cena);
Button john_cena_button = (Button) findViewById(R.id.john_cena_button);
john_cena_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (he_gay.isPlaying()){
he_gay.stop();
}
else if (john_cena.isPlaying()){
john_cena.seekTo(0);
} else{
john_cena.start();
}
}
});

how to play sound on button

i'm the newbie this my code
the sound is not play but when i click the button the toast is show
anyone help me??
public class DB_Parse extends Activity {
MediaPlayer mp;
Button button;
int ,sound;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.keterangan);
final int sound = iIdentifikasi.getIntExtra("dataID", 0);
button=(Button)findViewById(R.id.btnsound);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (sound==1){
mp = MediaPlayer.create(getApplicationContext(), R.raw.munfasil);
mp.start();
}
Toast.makeText(getApplicationContext(),
"Sound is Play", Toast.LENGTH_LONG).show();
}
});
}
}
if (sound==1) 1 from _id in sqlite
try this way it will work
public class DB_Parse extends Activity {
private static final String TAG = "MyActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(TAG, "Initializing sounds...");
final MediaPlayer mp = MediaPlayer.create(this, R.raw.youraudio);
Button play_button = (Button)this.findViewById(R.id.play_button);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Playing sound...");
mp.start();
}
});
Log.v(TAG, "Sounds initialized.");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Put your audio/media file in asset folder instead putting into raw folder and follow above snippet, its working quite fine for me..
try
{
AssetFileDescriptor afd = getAssets().openFd("your_media_file_name.mp3");
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
}
catch(Exception e)
{ e.printStackTrace();}
Fire it on your button click event
First of all you are declaring your variable sound twice.
Please change:
final int sound = iIdentifikasi.getIntExtra("dataID", 0);
for
sound = iIdentifikasi.getIntExtra("dataID", 0);
The other thing that you should try is changing the toast inside your if, so you are sure that sound is 1.
if (sound==1){
mp = MediaPlayer.create(getApplicationContext(), R.raw.munfasil);
mp.start();
Toast.makeText(getApplicationContext(),
"Sound is Play", Toast.LENGTH_LONG).show();
}
If toast is not displaying your int sound is not 1.

How to play, stop and pause working on media player instance in android ?

I want to develop media player type of application which has two button one for play and pause and one for stop. I take two image buttons in my layout file and reference it in Java file and code like this which I put here, but when I click on stop button audio is getting stopped but then I want replay audio file; but I cant play with play button.
my Java code below
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_aarti_fragment, container, false);
btnplay=(ImageButton)v.findViewById(R.id.btnplay);
btnstop=(ImageButton)v.findViewById(R.id.btnstop);
seekbar=(SeekBar)v.findViewById(R.id.seekbar);
mp = MediaPlayer.create(getActivity(), R.raw.arti);
btnstop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Stop",Toast.LENGTH_LONG).show();
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Pause",Toast.LENGTH_SHORT).show();
}
else
{ btnplay.setImageResource(R.drawable.ic_action_pause);
mp.start();
Toast.makeText(getActivity(), "Play",Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
Use This:
private BackgroundSound mBackgroundSound;
private MediaPlayer player;
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
player = MediaPlayer.create(HomePage.this, R.raw.background);
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
player.setLooping(true); // Set looping
player.setVolume(volume, volume);
player.start();
return null;
}
}
For Playing:
mBackgroundSound = new BackgroundSound();
mBackgroundSound.execute();
For Stop:
mBackgroundSound.cancel(true);
if (player != null) {
player.stop();
player.release();
}
For Pause:
if (player != null) {
player.pause();
}
Try this it will help you....
//Click Listener on Image Button with play and Pause method
PLAY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Play-Pause();
}
});
//Play Pause method...........
public void Play-Pause(){
if (mediaPlayer.isPlaying()) {
PLAY.setImageResource(R.drawable.pause);
mediaPlayer.pause();
} else {
PLAY.setImageResource(R.drawable.play);
mediaPlayer.start();
}
}
Once a media player is stopped, you need to call prepare on it again to get it to a state where you can call start(). Look at the state diagram here http://developer.android.com/reference/android/media/MediaPlayer.html#pause%28%29
Check this code, its better and simple solution !
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
Switch sw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this,R.raw.nokia);
sw = findViewById(R.id.sw);
sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mp.setLooping(true);
}
});
}
public void play(View v){
mp.start();
}
public void pause(View v){
if(mp.isPlaying())
mp.pause();
}
public void stop(View v){
if(mp.isPlaying()) {
boolean loop=mp.isLooping();
mp.stop();
mp = MediaPlayer.create(this, R.raw.nokia);
mp.setLooping(loop);
}
}
}

How to play and stop an mp3 file in an android app

I have created an app in eclipse to play and stop an mp3 file. Everything is just fine except that when I play the audio file and stop it and I want to replay it, the play btn does not wort! I was wondering if anybody can help me? Thanks in advance.
Here comes the code:
package ir.polyglotcenter.childrenmostfrequentwords;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Related to the media player
final MediaPlayer myMediaPlayer = MediaPlayer.create(Main.this, R.raw.audio);
//Button related to play btn
Button myButtonOne = (Button) findViewById(R.id.btn_audio);
myButtonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myMediaPlayer.start();
}
});
//Button related to stop btn
Button myButtonTwo = (Button) findViewById(R.id.btn_stop);
myButtonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myMediaPlayer.stop();
}
});
}
}
if you want to start /stop sound on Button Click then use MediaPlayer.start() and MediaPlayer.pause() to pause currently playing sound which start again on start button click . and override Activity onPause to finally stop and free MediaPlayer. make changes in your code as :
onStop Button Click :
myButtonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myMediaPlayer.pause(); //>>pause current sound
myMediaPlayer.seekTo(0); //>> seek to start it again
}
});
and override onPause method of Activity :
#Override
protected void onPause{
super.onPause();
myMediaPlayer.stop(); //>>> stop myMediaPlayer
myMediaPlayer.release(); //>>> free myMediaPlayer
}
Try this (just define Media Player in public area)
public class Main extends Activity {
MediaPlayer myMediaPlayer = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Related to the media player
myMediaPlayer = MediaPlayer.create(Main.this, R.raw.audio);
//Button related to play btn
Button myButtonOne = (Button) findViewById(R.id.btn_audio);
myButtonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myMediaPlayer.start();
}
});
//Button related to stop btn
Button myButtonTwo = (Button) findViewById(R.id.btn_stop);
myButtonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myMediaPlayer.pause();
}
});
}
}
the Point is implement MediaPlayer in the loop of if or any loop
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.buttonPlay:
//mp.reset();
mp=MediaPlayer.create(Ur Context.this, R.raw."ursong.mp3");
mp.start();
break;
case R.id.buttonStop:
mp.stop();
break;
}
}
You must move this code :
final MediaPlayer myMediaPlayer = MediaPlayer.create(Main.this, R.raw.audio);
in :
myButtonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final MediaPlayer myMediaPlayer = MediaPlayer.create(Main.this,R.raw.audio);
myMediaPlayer.start();
}
});

Categories

Resources