android play sound from sd-card - android

I need to play sound from sd card. I have method that must do this but it's doesn't work.
When I use this method:
public class AudioPlayService extends Service
{
MediaPlayer mMediaPlayer;
..............
public void soundplay(String adr)
{
mMediaPlayer = new MediaPlayer();
try
{
if (mMediaPlayer.isPlaying())
{
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(adr);
mMediaPlayer.prepare();
} catch (IOException e)
{
}
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mp.release();
mp = null;
}
});
}
Where String adr - it's absolute path to file on sd.
Then I call it:
AudioPlayService s = new AudioPlayService();
s.soundplay(iA.getSdDir() + "Files/Numbers/0.mp3");
and I get an err's:
12-09 13:04:13.829: E/MediaPlayer(16997): error (1, -2147483648)
12-09 13:04:13.829: E/MediaPlayer(16997): start called in state 0
12-09 13:04:13.829: E/MediaPlayer(16997): error (-38, 0)
12-09 13:04:13.839: E/MediaPlayer(16997): Error (-38,0)

I myself tried your code:
Mine worked fine when i put just "sdcard/1.mp3"
You ensure that the path is right or not
s.soundplay(iA.getSdDir() + "Files/Numbers/0.mp3");
Note:
If you are trying to make your method soundplay so as to stop previous audio and play the new audio file, then better would be not to perfom this inside that method
mMediaPlayer = new MediaPlayer();
Place this in constructor.
Otherwise each time you invoke s.soundplay(path) you will hear previous audio plus the new audio. ie,Previous one will not be stopped

player.start() put within try,catch block. Because if player not prepare your song ,still you are calling start method.start method is only called after playback is ready,
means prepare is success.Another thing is that you have to release the media player when your player is no longer.Otherwise there is so many player objects are running in back ground.

For some reason, your setDataSource() or Prepare() is failing. So after the exception, start()is giving the error, since the player is not in Prepared state. Add print statements in the catch block to know what is the exception. And move start() into the try catch block.
mMediaPlayer = new MediaPlayer();
try
{
if (mMediaPlayer.isPlaying())
{
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(adr);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e)
{
e.printStackTrace();
}

Related

MediaPlayer : Should have subtitle controller already set: KitKat

I am having an odd issue where my audio file sometimes plays and sometimes does not play. The catch is that when it decides to not play, the DDMS gives me an:
E/MediaPlayer﹕ Should have subtitle controller already set
Because this is one-to-one with the music not playing, I have determined that this is probably the issue...
If the music is not playing and I hit the volume button it begins to play.
If I wait about 30 seconds of no-play, it begins to start again (not looping).
Whats going on here? I am on KitKat using
player = new MediaPlayer();
AssetFileDescriptor afd = null;
try {
afd = getAssets().openFd("Theme.mp3");
} catch (IOException e) {
e.printStackTrace();
}
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
player.setLooping(true); //restart playback end reached
//player.setVolume(1, 1); //Set left and right volumes. Range is from 0.0 to 1.0
player.start(); //start play back
Looking at a previous discussion on StackOverflow, and the referenced Android commit where this was introduced, the code above might not completely initialize the MediaPlayer object.
The KitKat example code for media playback suggests that you should call:
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
immediately after you construct the MediaPlayer, and before you call its setDataSource method.
I had the same issue and I fixed it by adding the following right after instantiating MediaPlayer.
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (mp == mediaPlayer) {
mediaPlayer.start();
}
}
});
Previously I was implementing MediaPlayer.OnPreparedListener and overriding onPrepared() but it didn't work.
I hope this helps!
This should fix your problem (did for me): Replace the line that says "player.start()" following the rest of your code with an async callback like so:
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
This error is just a Log.e, not a real error. It shouldn't cause your player to not play, I'm guessing it's just because the player hadn't finished preparing when you try to call start().
E/MediaPlayer﹕ Should have subtitle controller already set
Its been a long time since I was working on this app. Here is what I ended up doing to get this to work. (Tested on KitKat and Lollipop). I think switching from MediaPlayer to APMediaPlayer was part of the trick.
#Override
public void onDestroy() {
if(player != null) {
player.release();
player = null;
}
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
if(player != null) {
player.start();
}
else {
player = new APMediaPlayer(this); //create new APMediaPlayer
player.setMediaFile("Theme.mp3"); //set the file (files are in data folder)
player.start(); //start play back
player.setLooping(true); //restart playback end reached
player.setVolume(1, 1); //Set left and right volumes. Range is from 0.0 to 1.0
}
}
#Override
public void onResume() {
super.onResume();
if(player != null) {
player.start();
}
}
set in manifest file may help you
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

android -how to program button next for playing new media

I already initialise a media by setDataSource and doing function prépare() start(). I want starting new média by click on button next, but what doing? Stop already media and do setDataSource and prépare()
Start() for next media?
Just reset mediaplayer before playing next song,then set new datasource and start it
public void startPlaying(String audioURL)
{
mediaPlayer.reset();
try
{
if(audioURL != null)
{
mediaPlayer.setDataSource(audioURL);
}
mediaPlayer.prepare();
mediaPlayer.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
You can set a callback when the playback of your MediaPlayer has finished. There you can set a new Datasource.

Android MediaPlayer IllegalStateException

I am trying to play an audio file in Eclipse using MediaPlayer in Android programming.
I need to run the audio file (.wav or .mp3) which is saved on computer hard-drive. I have tried many things. I also tried copying the file in res folder of my project, but nothing worked. Below is my code.
As you can see I have tried many ways and commented some. I was first getting IOException earlier. But after using MediaPlayer.create(), I am getting IllegalStateException.
Any help would be very appreciated.
public void playSound(MainActivity mainActivity){
System.out.println("in playsound");
MediaPlayer mp = null;
FileInputStream fis = null;
try {
//fis = new FileInputStream("C:\\Users\\Anupam-PC\\Downloads\\trailsoundfilerecordings\\jagmeet.wav");
//mp.setDataSource(fis.getFD());
System.out.println("inside try");
//mp.setDataSource("/res/raw/hai.wav");
//mp.setDataSource("C:\\Users\\Anupam-PC\\Downloads\\trailsoundfilerecordings\\jagmeet.wav");
//mp.setDataSource("android.resource://com.example.texttospeech/agreji.mp3");
//mp.setDataSource("agreji.mp3");
mp = MediaPlayer.create(mainActivity, R.raw.hai);
System.out.println("after DS");
mp.prepare();
System.out.println("after prepare");
mp.start();
// fis.close();
} catch (Exception e) {
System.out.println(e);
} finally{
try{
fis.close();
} catch (Exception e){
}
}
You don't need to implement mp.prepare();, you have create(/**/)
This is my example that works like a charm:
class Vulcan implements MediaPlayer.OnPreparedListener{
MediaPlayer mediaPlayer = null;
...
boolean isPrepearedToPlayAudio = false;
mediaPlayer=MediaPlayer.create(context,R.raw.mini_vulcan_gun_1);
mediaPlayer.setOnPreparedListener(this);
public void stop(){
mediaPlayer.pause();
}
public void start(){
if(isPrepearedToPlayAudio){
mediaPlayer.start();
mediaPlayer.setLooping( true );
}
}
#Override
public void onPrepared(MediaPlayer mp) {
isPrepearedToPlayAudio = true;
}
Your invocation of MediaPlayer.create(...) already calls prepare(), and multiple calls to prepare() will cause an ISE. All you need to do is remove:
mp.prepare();
Javadoc:
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.
When done with the MediaPlayer, you should call release(), to free the resources. If not released, too many MediaPlayer instances will result in an exception.

Playing media in Android

my app is playing some audio files, but if the user hits the play button twice, it will play then it will play again (something like that).
I would like the next action to happen JUST when the first execution of the audio file is over.
How can I do that?
Here is my code:
MediaPlayer mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource((endMidia));
mMediaPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
mMediaPlayer.start();
Any help is appreciatted!
You can make check with MediaPlayer.isPlaying().
There are listeners on MediaPlayer events like OnCompletionListener
http://developer.android.com/reference/android/media/MediaPlayer.html#setOnCompletionListener(android.media.MediaPlayer.OnCompletionListener)
and others
check if condition as shown in below code
MediaPlayer mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource((endMidia));
mMediaPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
if(!mMediaPlayer.isPlaying()){
mMediaPlayer.start();
}

(Android MediaPlayer) How am I supposed to call setAudioStreamType() if MediaPlayer.create() implicitly calls prepare()?

I am writing an Android alarm application that uses a Service in order to play the alarm tone. Currently, I am able to get the audio to play, but it plays in a form that can be muted by turning down the device's volume. Thus, I am trying to add a call to setAudioStreamType(AudioManager.STREAM_ALARM); to prevent this.
I have the following for my onStartCommand() function for the service:
MediaPlayer mMP;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
try
{
mMP = MediaPlayer.create(this, R.raw.alarm);
mMP.setAudioStreamType(AudioManager.STREAM_ALARM);
mMP.setLooping(true);
//mMP.prepare(); commented out since prepare() is called in create
}
catch (Exception e)
{
e.printStackTrace();
}
if (mMP != null) mMP.start();
return START_STICKY;
}
My problem is that with the call to setAudioStreamType(), the MediaPlayer never plays the audio. If I comment that line out, the audio plays.
With the line in, I get the following runtime error(s):
04-10 19:32:03.115: E/MediaPlayer(3411): setAudioStream called in state 8
04-10 19:32:03.115: E/MediaPlayer(3411): error (-38, 0)
04-10 19:32:03.115: E/MediaPlayer(3411): start called in state 0
04-10 19:32:03.115: E/MediaPlayer(3411): error (-38, 0)
04-10 19:32:03.115: E/MediaPlayer(3411): Error (-38,0)
04-10 19:32:03.115: E/MediaPlayer(3411): Error (-38,0)
Some research (I can't find the link now) told me that setAudioStreamType() can't be called after prepare() has been called, and that create() implicitly calls prepare().
In any regard, how am I supposed to setAudioStreamType() without such an error?
You can either call mp.reset() and then set the stream type, data source, and then prepare. Alternately just use the default constructor and handle the initialization yourself.
EDIT:
Resources res = getResources();
AssetFileDescriptor afd = res.openRawResourceFd(R.raw.alarm);
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setLooping(true);
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();
Accepted answer was throwing an IllegalStateException. This is working
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(
this,
getCustomToneUri()
);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources