My app Doesn't work in playing video and audio files. I use internal storage for saving the audio video files.here is my code video and audio doesn't play the error showing my code is :Attempt to invoke virtual method 'void android.media.MediaPlayer.setDataSource(java.lang.String)' on a null object reference
public class VideoFileActivity extends Activity {
String filePath, fileName;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.activity_video_dialogue);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.ic_launcher);
SharedPreferences pref = getSharedPreferences("import_pkid", MODE_PRIVATE);
filePath = pref.getString("file_path", "");
fileName = pref.getString("file_name", "");
Bundle extras = getIntent().getExtras();
if(extras != null){
filePath = extras.getString("file_path");
fileName = extras.getString("file_name");
}
DownloadFiles();
MusicPlay();
}
public void DownloadFiles() {
//Downloads Files
}
public void MusicPlay()
{
try {
mp.setDataSource(filePath+"/"+fileName);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.setLooping(true);
mp.start();
}
}
use log statement to get value of filePath and fileName
i use mp.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/......./" + name.mp3) for playing internally saved audios
You forgot to initialize MediaPlayer.
Add the following before calling methods on 'mp' .
MediaPlayer mp=new MediaPlayer();
Related
I have problem with playing mp3 from asset folder. When i try to change image on button, mp3 stops playing(not always...)
Error that im getting
W/MediaPlayer-JNI: MediaPlayer finalized without being released
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(enableMusic){
playMusic();
}
...
private void playMusic() {
boolean noAudioFile = false;
Context context = this; // or ActivityNotification.this
MediaPlayer mpMusic = new MediaPlayer();
AssetManager mg2 = getResources().getAssets();
String musicPath = langFolder+audioFolder+"system/Bubble_Bath.mp3";
try {
mg2.open(musicPath);
} catch (IOException ex) {
noAudioFile = true;
}
if(!noAudioFile) {
AssetFileDescriptor descriptor = null;
try {
descriptor = context.getAssets().openFd(musicPath);
} catch (IOException e) {
e.printStackTrace();
}
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
try {
mpMusic.setDataSource(descriptor.getFileDescriptor(), start, end);
} catch (IOException e) {
e.printStackTrace();
}
}
else{
}
mpMusic.setVolume(5,5);
try {
mpMusic.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mpMusic.start();
mpMusic.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.start();
}
});
}
public void nextCard(View view) throws IOException {
i++;
if (i==files.length) i=0;
if(i>-1){
Button btnNext = (Button)findViewById(R.id.btnNext);
btnNext.setText("Next");
}
Drawable d = Drawable.createFromStream(getAssets().open(categoryPath+"/"+files[i]+".png"), null);
findViewById(R.id.btnImage).setBackgroundDrawable(d);
if(files[i].substring(0,1).contains("a") || files[i].substring(0,1).contains("i")){
startFileSound = langFolder + audioFolder + "system/GAME_thisisan.mp3";
}
else if (files[i].substring(files[i].length()-1,files[i].length()).contains("s")){
startFileSound = langFolder + audioFolder + "system/GAME_theseare.mp3";
}
else{
startFileSound = noAudioFileSound;
}
}
When i'll try to comment line below, mp3 is playing with no problem.
Drawable d = Drawable.createFromStream(getAssets().open(categoryPath+"/"+files[i]+".png"), null);
you are loading drawable from asset folder, that is correct. But Don't do in the main thread. Try to do this in different thread.
Don't ever create MediaPlayer like this
MediaPlayer mpMusic = new MediaPlayer();
Use
MediaPlayer.create(context,R.raw.music);
try close descriptor
mpMusic.setDataSource(descriptor.getFileDescriptor(), start, end);
descriptor.close();
I implemented a file chooser on a media player which returns the file paths for an .mp3 and an .srt on the externalSD. The audio plays fine. But when I call addTimedTextSource with the path to the .srt, it throws a null pointer exception. So, I put in an If(file.exists). It also returns a null. I tried moving the file to the internal SD with the same result. Any ideas?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
buttonPause = (Button) findViewById(R.id.buttonPause);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
Bundle bundle = getIntent().getExtras();
if(bundle!=null) {
String removeString = "file:";
soundPath = bundle.getString("soundFile");
subPath = bundle.getString("subFile");
subPath = removeString(subPath,removeString);
soundFile = new File(soundPath);
subFile = new File(subPath);
}
player = new MediaPlayer();
try {
player.setDataSource(soundPath);
player.setOnErrorListener(this);
player.setOnPreparedListener(this);
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onPrepared(MediaPlayer mp){
mp.setOnTimedTextListener(this);
if(subFile.exists() {
try {
player.addTimedTextSource(subFile.getAbsolutePath(), MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
} catch (IOException e) {
Log.v("Hey Here is a Problem: ", e.getMessage());
}
TrackInfo[] ti = player.getTrackInfo();
for (int i = 0; i < ti.length; i++) {
if (ti[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT) {
player.selectTrack(i);
break;
}
}
}else{
onBackPressed();
}
mp.start();
}
Edit:
Rereading your question, it appears that subfile.exists() returns true, but you get a null pointer exception when you try to call player.addTimedTextSource().
Assuming player is not null, I'd like you to try this:
string fileStr = subfile.getAbsolutePath();
player.addTimedTextSource(fileStr, MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
I suspect that you may be running into an issue with the overloads of addTimedTextSource().
Old answer:
So, I put in an If(file.exists). It also returns a null. I tried
moving the file to the internal SD with the same result. Any ideas?
There is no file at the provided path. Since you have moved the file, seems like you're mistyping the file name.
I am using a method to initialize and prepare a MediaPlayer (defined as class variable). It takes a String which is the name of the song as its parameter and it sets the DataSource to that particular path.
public void create_and_prepare_song(String x) {
if (mp != null)
mp.release();
mp = new MediaPlayer();
String filePath = Environment.getExternalStorageDirectory().getPath() + "/songsfolder/" + x + ".mp3";
try {
mp.setDataSource(filePath);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Now, somewhere inside my code I use this method to initialize and prepare "1.mp3". Then, as soon as this song is finished, I use an onCompletionListener so that "2.mp3" is played after, and "3.mp3" then. I use:
create_and_prepare_song("1");
i = 2;
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (i <= 3) {
String int_to_String = i + "";
create_and_prepare_song(int_to_String); //1
mp.setOnCompletionListener(this);
mp.start();
i++;
}
}
});
mp.start();
Now, this causes app to stop from working! However, if I just copy and paste the body of the method to the //1 line instead, the app works fine, playing first, second and third song. Why is that so? Thanks a lot
Note that you are creating a new player inside of create_and_prepare_song() but the old one is still referenced inside of the listener.
That's because the global variable and the onCompletion parameter has the same name: mp.
Here's piece of code that works:
package com.example.simon.mplaylist;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import java.io.IOException;
/**
* Created by Simon on 2014 Jul 20.
*/
public class MainActivity extends Activity {
static int currentSong;
static MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mediaPlayer != null)
return;
currentSong = 1;
create_and_prepare_song(currentSong);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (currentSong++ >= 3) {
mediaPlayer = null;
return;
}
create_and_prepare_song(currentSong);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
});
mediaPlayer.start();
}
public void create_and_prepare_song(int songNum) {
if (mediaPlayer != null)
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
String storage = Environment.getExternalStorageDirectory().getPath();
String filePath = storage + "/songsfolder/" + String.valueOf(songNum) + ".mp3";
try {
mediaPlayer.setDataSource(filePath);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE also that I defined the MediaPlayer as static and also am checking # onCreate for it's presence. That way you avoid multiple songs playing at once if the activity is recreated (e.g. screen rotation).
You really shouldn't be starting actual playback inside create_and_prepare_song(). It should be started inside onPrepared() since there might be some delay from the call to prepare() and the media being ready to play.
I tried to implement bassboost effect in android..but there is no effect..I used the following code for bassboost effect;(I tried using global audio session id and i added permissions in manifest file)-->modify audio settings..
enter code here
BassBoost boost = new BassBoost(0,mp.getAudioSessionId());
boost.setEnabled(true);
boost.setStrength((Short)1000);
mp.attachAuxEffect(boost.getId());--->if i use this i'm getting(-38,0) or else no effect
mp.setSendLevel(1.0f);
I used below code for bass boost effect.got media player(-38,0) error..please resolve this issue..
enter code here
public class MainActivity extends Activity
{
MediaPlayer mediaplayer;
AssetFileDescriptor descriptor;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.activity_main);
mediaplayer = new MediaPlayer();
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
descriptor = MainActivity.this.getAssets().openFd("Kalimba.mp3");
} catch (IOException e1) {
e1.printStackTrace();
}
try {
mediaplayer.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(), descriptor.getLength());
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
descriptor.close();
} catch (IOException e1) {
e1.printStackTrace();
}
setUpBooster();
mediaplayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
public void setUpBooster() {
BassBoost booster = new BassBoost(0,0);//-->tried with sessionid also
booster.setStrength((short) 1000);
booster.setEnabled(true);
mediaplayer.attachAuxEffect(booster.getId());
mediaplayer.setAuxEffectSendLevel(1.0f);
try {
mediaplayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
error 38 means you are asking the MediaPlayer to do something when in the wrong state. You won't be able to fathom your error just from this.
And anytime you call setDataSource() on it you will need to prepare() it again. Think of it as loading the file, getting ready for playback.
Edit
You have already attached your bassboost with your mediaplayer when it created. So remove this mp.attachAuxEffect(boost.getId());
I have an activity which has a series of buttons which when pressed should play an audio file. I have been trying to implement this using MediaPlayer however I cant get it to work.
Here is the code I have been trying:
final MediaPlayer mp = new MediaPlayer();
Button ger1play = (Button) findViewById(R.id.ger1play);ger1play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.setDataSource(this, R.raw.greet_1);
mp.prepare();
mp.start();
}
});
The setDateSource method doesnt seem to work, can anyone tell me where I am going wrong?
I would like to then set the mediaPlayer to the relevant audio file based on which button is pressed, is this possible?
Updated
final MediaPlayer mp = new MediaPlayer();
Button ger1play = (Button) findViewById(R.id.ger1play);ger1play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Uri myUri = Uri.parse(R.raw.greet_1);
mp.setDataSource(GreetingsLesson.this, R.raw.greet_1);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
try this:
final MediaPlayer mp = new MediaPlayer();
Button ger1play = (Button) findViewById(R.id.ger1play);ger1play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mp.setDataSource(CurrentActivity.this, R.raw.greet_1);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
Ifyou want to send the media player object with one of the files fromapplication raw resources or from application assets files you can dothat as follows:
try {
AssetFileDescriptor fd = getResources().openRawResouceFd(R.raw.greet_1);
mp.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
mp.start();
fd.close();
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
Why not just use
mp = MediaPlayer.create(this, R.raw.greet_1);
Then you don't need the prepare or start.
Are you running this in an emulator? If so check your AVD manager has under hardware, the property "Audio playback support | yes" added