for recording file output, I use MediaPlayer.
usually, When I button clicked, start media file.
but, sometime not sound play.
/MediaPlayer: mediaplayer went away with unhandled events
W/MediaPlayer-JNI: MediaPlayer finalized without being released
at first I think before the voice file is finished, when clicked button occur this problem.
but even if I press the button repeatedly, sometime not sound play.
source.
player = new MediaPlayer();
player.reset();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.reset();
AssetFileDescriptor assetFileDescriptor =
getApplicationContext().getResource().openRawResourceFd(R.raw.sound);
player.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (player != null) {
player.stop();
player.release();
}
}
});
How to fix sometimes not sound play when i button clicked?
thanks.
There's no reason to call MediaPlayer.release() if it will be used again, as calling reset() will release all the memory & codecs that are in use.
init:
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.reset();
}
});
Handling button clicks:
void onButtonClicked() {
player.reset();
AssetFileDescriptor assetFileDescriptor =
getApplicationContext().getResource().openRawResourceFd(R.raw.sound);
player.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
player.prepare();
player.start();
}
Related
I am making a android simple media player for playing a audio files and facing a problem with it.
I want to stop Chronometer and media player
When the current Duration of playing file == total duration of file..?
Here is my demo code.
private void playAudio() {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(outputFile);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
mediaPlayer.start();
long totalDuration = mediaPlayer.getDuration();
Log.i("MediaPlayer", String.valueOf(totalDuration));
}
here is another code added from answer .
i add the listrner
mediaPlayer.setOnCompletionListener(CompletionListener);
MediaPlayer.OnCompletionListener CompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
long totalDuration = mp.getDuration();
}
};
Use onCompletionListener to check when media player has reached end of the media file.
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// do your task
}
});
For further reference see this link
Media Player
I need the method that my app run multiple mp3s. Each mp3 must play after previous mp3.
I created method that play sound
void PlaySentence(String path){
try {
AssetFileDescriptor afd = getAssets().openFd(path);
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();
}
catch (Exception ex)
{
if (BuildConfig.DEBUG)
Log.d(TAGName, ex.getMessage());
}
}
Then I call that function in OnCreate. I used while loop for playing all mp3 files. But sound mixed to each other. If I use loops and isPlaying method the application didn't respond.
while (currentMp3<totalMp3) {
if (!player.isPlaying()) {
PlaySentence();
}
}
Also I use below method for avoid of mixing sounds. It work for one mp3
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
PlaySentence();
}
});
What is the best solution to do that?
You should use setOnCompletionListener, but declare your player as a class member, initalize it in onCreate, and don't create a new one for each mp3. PlaySentence should be something as:
void PlaySentence(String path){
try {
AssetFileDescriptor afd = getAssets().openFd(path);
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();
}
catch (Exception ex)
{
if (BuildConfig.DEBUG)
Log.d(TAGName, ex.getMessage());
}
}
I'm having an issue with some android code to play a sound notification on certain events.
Here's the code:
int result = audioManager.requestAudioFocus(MainRunningService.afChangeListener,AudioManager.STREAM_NOTIFICATION,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mp = new MediaPlayer();
mp.setDataSource(context, soundToPlay);
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mp.prepare();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
try {
Log.d(LOGTAG, "SoundService MUSIC: MUSIC IS NOW COMPLETE");
mp.release();
mp = null;
Log.d(LOGTAG, "SoundService MUSIC: MUSIC IS NOW COMPLETE - RELEASED");
} catch (Exception e) {
e.printStackTrace();
}
}
});
mp.setLooping(false);
mp.start();
}
else{
Log.w(LOGTAG, "SoundService Audiofocus was not granted");
}
What I'm finding is that sometimes it will play, whereas other times it won't play. When it doesn't play it's hitting the "SoundSerice Audiofocus was not granted" log line. I've looked at the system logs, but can't find anything that says why it's not been granted.
Once this has happened, then every request seems to fail.
Does anyone have any pointers to what I might be doing wrong?
//call the method playAssistClip() on button click or wherever you want.
private MediaPlayer mp;
private void playAssistClip() {
if (workoutReps.equalsIgnoreCase("6x6x6")) {
mp = MediaPlayer.create(ProcessWorkout.this,
R.raw.six_six_six_formated_ogg);
mp.setOnCompletionListener(new OnCompletionListener() {
//do something after the audi ends
mp.reset();
mp.release();
finish();
}
});
mp.start();
//to get the duration of clip
spentTimeOnWorkout = mp.getDuration();
}
I have a lot of short .mp3 files that I want to play one after the other.. I tried to use onCompletion event and start the next mp3, though this causes a brief gap between the 2 mp3s..
Here is the code:
void StartSound() {
mediaplayer = MediaPlayer.create(this, Uri.parse(FILE_PATH + counter + ".mp3"));
try {
mediaplayer.start();
mediaplayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
counter++;
try {
mp.reset();
mp.setDataSource(FILE_PATH + counter + ".mp3");
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mp.start();
}
});
} catch (Exception e) {
}
}
Is there a work around to this issue?
There's a workaround, but whether it's worth the trouble is up to you.
The basic idea is to decode the MP3 files to a PCM buffer, stitch them together in a byte array, and play with an AudioTrack. Seamless MP3 playback doesn't really exist with MediaPlayer. This could be a pain in the ass, though, and memory problems are likely if you're talking about full songs. For short clips, it may work, but SoundPool might be the better option.
If you're just trying to narrow the gap a bit, you can try preparing the following MediaPlayer objects before onCompletionListener. Instead of waiting to be done, prepare the next two so you can start playback faster. Then when you hit onCompletion, you can just flip which object you're using and start(). Crude double buffering, in a way.
Try this:
public class MainActivity extends Activity
{
private int[] tracks = {R.raw.explosion,R.raw.pianothingy_one,R.raw.car_horn_x};
int mCompleted = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp = MediaPlayer.create(this, tracks[0]);
mp.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mCompleted++;
mp.reset();
if (mCompleted < tracks.length)
{
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (mCompleted>=tracks.length)
{
mCompleted =0;
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else
{
mCompleted=0;
mp.release();
mp = null;
}
}
});
mp.start();
i am playing mp3 sound using default media player of android, my code for plying sound below
MediaPlayer mp=MediaPlayer.create(hello.this,R.raw.abc);
if(mp!=null)
{
mp.start();
}
i need to play same sound on same button click. when i click continuously on button after some time sound is not working and i getting error MediaPlayer(7395): error (-19, 0).
Does any body have idea for this issue,
Please send me
Thank in advance.
call
mp.reset();
because ever time you are decalaring object
or declare on class level Mediaplayer OBject
Make global variable of mediaplayer and try this way
MediaPlayer mp;
if (mp!=null) {
mp.stop();
mp.release();
}
mp= MediaPlayer.create(hello.this,R.raw.abc);
mp.start();
mp = new MediaPlayer();
mp.create(this, R.raw.testmed);
mp.setVolume(100, 100);
mp.setOnPreparedListener(this);
mp.prepare();
Then you will need to define this and it should work:
public void onPrepared(MediaPlayer player) {
mp.start();
}
you can play music like below
// for play the song
MediaPlayer mp = new MediaPlayer();
try
{
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
btnPlay.setBackgroundResource(R.drawable.img_btn_pause);
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
I have found solution for this issue. i have correct this issue using below code, May help other also.
Thanks
Call Method like
PlaySound(R.raw.abc);
//Method
private void PlaySound(int Sound_id)
{
mplayer = MediaPlayer.create(Act_Oceanwaves.this,Sound_id);
if(mplayer!=null)
{
mplayer.start();
}
mplayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mp.release();
}
});
}