I am making a simple media player application. It involes a textfield (et) where user just enters the exact name of the song to be played and presses the play button (ib1) to be played. Songs are saved inside sdcard. My code is:
ib1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String value = et.getText().toString();
String full_path = "/mnt/media_rw/sdcard/mymusic/" + value + ".mp3";
et.setText("");
mp = new MediaPlayer();
mp.setDataSource(full_path);
mp.prepare();
mp.start();
} });
But this produces Media Player error (-38.0). So, following Media Player called in state 0, error (-38,0) I tried to replace the mp lines with:
mp.setDataSource(full_path);
mp.setOnPreparedListener(null);
mp.prepareAsync();
mp.start();
But it won't work either, producing error (1, -2147483648). Can someone help me or make some suggestions for the code? Thanks a lot
You need to call mediaPlayer.start() in the onPrepared method by using a listener. You are getting this error because you are calling mp.start() before it has reached the prepared state.
Here is how you can do it :
mp.setDataSource(full_path);
mp.setOnPreparedListener(this);
mp.prepareAsync();
public void onPrepared(MediaPlayer player) {
player.start();
}
Related
I'm creating a simple soundboard to play sounds when a user clicks a button. Problem is, if the button is pressed enough ( usually around 10 times ) it will eventually stop playing and show the error E/MediaPlayer: error (1, -19)
what am I doing wrong? My code that plays the sound:
private void playSound(int soundID){
final MediaPlayer mp = MediaPlayer.create(this,soundID);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
}
});
}
You should use Soundpool. It's created exactly for playing short sound effects. And it's much simpler to use than MediaPlayer. MediaPlayer should only be used for playing regular/large music.
See here for example:
http://www.vogella.com/tutorials/AndroidMedia/article.html#tutorial-play-sounds-via-soundpool
Note: No need to use onTouch as in the example, you can just use onClick for simplicity.
Reason: "W/Choreographer: (let say) Frame time is 0.239384 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase."
i.e, there is a much gap between timestamps.
This problem can be removed by using setOnCompletionListener() within your OnClick() method like: `
#Overrid
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Get the {#link Word} object at the given position the user clicked on
Word word = words.get(position);
Log.v("NumbersActivity","Current word: "+word);
// Create and setup the {#link MediaPlayer} for the audio resource associated with the current word
MediaPlayer mMediaPlayer = MediaPlayer.create(NumbersActivity.this, word.getAudioResourceId());
// Start the audio file
mMediaPlayer.start();
// Keep timeStamp sync
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mMediaPlayer.release();
}
});
}
`
private void playSound(int soundID){
final MediaPlayer mp = MediaPlayer.create(this,soundID);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mp.release();
}
});
}
i try to stream and play an audio file in my application. i use this code :
MediaPlayer player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(url);
player.prepare();
player.start();
i want to know is it possible to detect when player finished playing ? i want to change a button color after player finished playing
Check out the setOnCompletionListener method:
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "Done playing!");
}
});
You can actually set a ton of callbacks here. In addition to setOnCompletionListener, we have:
setOnBufferingUpdateListener
setOnErrorListener
setOnInfoListener
setOnPreparedListener
setOnSeekCompleteListener
setOnTimedMetaDataAvailableListener
setOnTimedTextListener
setOnVideoSizeChangedListener.
So basically I use a Spinner widget and pass it the RingtoneManager Picker action, the user then selects their ringtone. Then I call onActivityResult() and get the uri for the ringtone.
Finally I pass the uri to another activity where I have a alarm setup to go off after a specific amount of time.
THE PROBLEM >>> when I get the uri for the ringtone in the 2nd activity and let mediaPlayer play it, It...it doesn't stop. No matter WHAT I try.
This is the 2nd activity and the mediaPlayer that never stops.
Uri ringtone;
ringtone = Uri.parse(musixType);
//mMediaPlayer.setDataSource(DisplayNotification.this, ringtone);
mMediaPlayer = MediaPlayer.create(DisplayNotification.this, ringtone);
mMediaPlayer.start();
mMediaPlayer.setVolume(100, 100);
}
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
while (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
});
How do I get it to stop #.#
Edit:
Could the reason it doesn't stop playing be that it is a ringtone from the RingtoneManager? I don't know why this would matter but I'm grasping at straws at this point.
Edit:
Is there a way to specify a certain length of time for mediaPlayer to run and disregard the data passed to it?
did you use MediaPlayer.setLooping method
use mMediaPlayer.setLooping(false);
Since you're not calling setLooping(true); on your mMediaPlayer referenced object, looping should not be the issue here as default is set false. Make sure you're not actually calling this piece of code multiple times from outside. Put a Log line before mMediaPlayer = MediaPlayer.create(DisplayNotification.this, ringtone); and see how many times it gets logged.
use this
mMediaPlayer.setLooping(true);
I had this problem too and solved it like this:
player.setDataSource(this, ringtone);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mp) {
myHandler.postDelayed(new Runnable() {
#Override
public void run() {
mp.stop();
mp.release();
}
}, mp.getDuration()); <-- Make a postDelayed runnable that has the duration of the file as its cut off. Once the song plays, it will stop the mediaPlayer.
mp.start();
}
});
In Adnroid, at first i declare the mediaplayer by
MediaPlayer mpl;
next I have this in the onCreate method
mp = new MediaPlayer();
mp = MediaPlayer.create(this, R.raw.hit );
mp.setVolume(1, 1);
and a function that's supposed to play a sound when called
public void click()
{
mp.start();
}
yet the problem is that if the user calls this function multiple times, before it has stopped playing the last sound, it will die and stop playing any sounds, before the app is reset.
Any ideas how to fix that?
Thanks!
edit - found a solution:
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mpl.release();
}
});
public void click()
{
if( ! mp.isPlaying() ) {
mp.start();
}//if
}//met
you can disable the button.
or you can stop current playing and star
new in onClick()
I am trying to play a few music (wav format) files based on button clicks. I am unable to get MediaPlayer to work properly. Every time I try to instantiate an object of MediaPlayer class, it fails on create(). Before I post the code, here is a run-through of what I am doing:
1. A layout file that contains 2 buttons.
2. Those buttons are read and onClickListeners defined for them.
3. Depending on the button clicked, a function called playAudioFile(View) called which creates the MediaPlayer instance and plays the file. The code for playAudioFile(View) is as follows:
public void playAudioFile(View v) {
/*Steps:
* 1. Take in id of the button.
* 2. Using id, identify what file needs to be played.
* 3. Play file.
*/
String path_to_file = null; //this is the path to the file.
if(b01.getId() == ((Button)v).getId()) {
Log.v(this.toString(), "Button 01 pressed.");
path_to_file = "/sdcard/audio/temp1.wav";
} else if(b02.getId() == ((Button)v).getId()) {
Log.v(this.toString(), "Button02 pressed.");
path_to_file = "/sdcard/audio/temp2.wav";
}
path_to_file = "file://" + path_to_file;
Uri streamUri = Uri.parse(path_to_file);
Log.v(this.toString(), "Path of file = " + path_to_file);
MediaPlayer mp = MediaPlayer.create(this, streamUri);
if(mp == null) {
Log.v(this.toString(), "Create() on MediaPlayer failed.");
}
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
try {
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
Log.v(this.toString(), "Illegal state exception thrown in start.");
}
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
}
I have gone through a lot of posts here on stackoverflow that detail solutions to the above problem. I am encountering this problem after having incorporated all the suggestions made therein. Any help is most welcome.
Thanks,
Sriram
I dont understand why you are trying to do
MediaPlayer mp = MediaPlayer.create(this, streamUri);
This is my implementation of my Player, Hope this will help you in some way:
MediaPlayer mp = new MediaPlayer();
setContentView(R.layout.player);
Intent intent = getIntent();
String path = "";
System.out.println("My Scheme : "+intent.getData().toString().substring(8));
if (intent.getData().getScheme().equals("video")) {
path = intent.getData().toString().substring(8);
System.out.println("Path : "+path);
if(path.endsWith(".mp3")) {
setContentView(R.layout.musicplayer);
setContentView(R.layout.controls);
Log.e("MusicPlayer", "Playing: " + path);
try {
Notification notification = new Notification(
R.drawable.playbackstart, path, System.currentTimeMillis());
nm.notify(NOTIFY_ID, notification);
mp.reset();
mp.setDataSource(path);
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
System.out.println("Hi i am at the End");
}
});
}catch {expression}
If I'm not wrong, you can't use onPrepare because mp.prepare() is called inside MediaPlayer.create(). The simpliest code can be something like this:
MediaPlayer mp = MediaPlayer.create(this, streamUri);
mp.start();
If you want something more elaborated, you can try this:
MediaPlayer mp = MediaPlayer.create(this, streamUri);
if(mp == null) {
Log.v(this.toString(), "Create() on MediaPlayer failed.");
} else {
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//here you should call the methods to release memory
mp.stop();
mp.release();
}
});
mp.start();
}
Tell me if it helped you.
PD: Is better if you use a device for testing rather than a simulator. Some classes don't work properly there (MediaPlayer can't reproduce video in simulators) and I don't remember if it supports audio.
As far as I understand your problem: You are calling the MediaPlayer.create(...) method, and it returns null, meaning the creation of a MediaPlayer instance failed. According to the accepted answer of this post MediaPlayer.create() always returns null it is due to a corrupted audio file.
I also have an issue, where the sound gets played but on rare occasions the create() method also returns null. I use sounds in a turn based game, after each turn a sound is played. I always call the create method, start the player and release it when it's done. That happens every turn and like once in 300 turns the create method returns null... So in my case it must be something else. In yours it could probably have something to do with the corruption of the mp3 file.