Android development studio error with MediaPlayer object - android

Getting an error in intellij that states I have not defined a onPrepared method in my setOnPreparedListener class. Have reviewed the documentation and my code for the onPrepared method matches what's defined.
Code:
import android.app.IntentService;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
/**
* Created by tim on 4/19/2017.
*
*/
public class TonePlayerIntentService extends IntentService implements MediaPlayer.OnErrorListener,
MediaPlayer.OnPreparedListener,
MediaPlayer.OnCompletionListener{
private static final String LOG_TAG = "actotracker " + TonePlayerIntentService.class.getSimpleName();
MediaPlayer mMediaPlayer = null;
Uri chime = null;
public TonePlayerIntentService() {
super(LOG_TAG);
}
/**
* called everytime an intent is launched
*/
#Override
public void onCreate() {
super.onCreate();
chime = Uri.parse("android.resource://"+getApplicationContext().getPackageName()+"//raw//chime.mp3");
}
/**
* Handles incoming intents.
* #param intent The Intent is provided (inside a PendingIntent) when requestActivityUpdates()
* is called.
*/
#Override
protected void onHandleIntent(Intent intent) {
Log.d(LOG_TAG,"IN onHandleIntent");
this.onStartCommand();
}
public int onStartCommand(){
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setLooping(false);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mMediaPlayer.setDataSource(getApplicationContext(), chime);
}catch (IOException ie){
DatabaseProcessor.getInstance().logErrorEvent(ie);
}
mMediaPlayer.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener(){
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
cleanUpPlay();
return true;
}
});
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
cleanUpPlay();
}
});
return 1;
}
public void cleanUpPlay(){
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
The error message states that onPrepared(MediaPlayer) must be defined in the setOnPreparedListener class.
Would appreciate information on what I did wrong. Happily provide more information if requested.
Updated with complete code.

Try calling mMediaPlayer.prepareAsync(); after you have set your OnPreparedListener
Edit: remove implements and the classnames behind it. Your class is not implementing any interfaces, since you are implementing them inline, and remove this line as well.
mMediaPlayer.setOnCompletionListener(this);

Related

How to make service for Play Pause of music Player

Here is my code which is play song from the resources folder and now I am stuck with service so please help me.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler=new Handler();
seekBar=findViewById(R.id.seekBar);
mp=MediaPlayer.create(MainActivity.this,R.raw.ed);
final int Duration=mp.getDuration();
Media Player Prepared Listener.....
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
updateSeekBar();
mp.start();
}
});
Runnable Thread for Seekbar.....
runnable=new Runnable() {
#Override
public void run() {
updateSeekBar();
}
};
Phone State Listener for Incoming and Outgoing Calls.....
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
mp.pause();
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
mp.start();
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
mp.pause();
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager)
getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
}
Seek Bar Update Method....
private void updateSeekBar() {
seekBar.setProgress(mp.getCurrentPosition());
mHandler.postDelayed(runnable, 100);
}
}
Now, it's my service code.......
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
public class MyMusicService extends Service {
On Create method of service....
#Override
public void onCreate() {
super.onCreate();
}
On start method of service....
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
On Destroy method of service....
#Override
public void onDestroy() {
super.onDestroy();
}
Binder of Service.....
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
see i have added the code of service which is work for me.
you can try this code for your need
package com.example.musicplayer;
import java.util.ArrayList;
import java.util.Random;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
/*
* This is demo code to accompany the Mobiletuts+ series:
* Android SDK: Creating a Music Player
*
*/
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
//media player
private MediaPlayer player;
//song list
private ArrayList<Song> songs;
//current position
private int songPosn;
//binder
private final IBinder musicBind = new MusicBinder();
//title of current song
private String songTitle="";
//notification id
private static final int NOTIFY_ID=1;
//shuffle flag and random
private boolean shuffle=false;
private Random rand;
public void onCreate(){
//create the service
super.onCreate();
//initialize position
songPosn=0;
//random
rand=new Random();
//create player
player = new MediaPlayer();
//initialize
initMusicPlayer();
}
public void initMusicPlayer(){
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set listeners
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
//pass song list
public void setList(ArrayList<Song> theSongs){
songs=theSongs;
}
//binder
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
//activity will bind to service
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
//release resources when unbind
#Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
//play a song
public void playSong(){
//play
player.reset();
//get song
Song playSong = songs.get(songPosn);
//get title
songTitle=playSong.getTitle();
//get id
long currSong = playSong.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
//set the data source
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
//set the song
public void setSong(int songIndex){
songPosn=songIndex;
}
#Override
public void onCompletion(MediaPlayer mp) {
//check if playback has reached the end of a track
if(player.getCurrentPosition()>0){
mp.reset();
playNext();
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.v("MUSIC PLAYER", "Playback Error");
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
mp.start();
//notification
Intent notIntent = new Intent(this, MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setSmallIcon(R.drawable.play)
.setTicker(songTitle)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(songTitle);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
//playback methods
public int getPosn(){
return player.getCurrentPosition();
}
public int getDur(){
return player.getDuration();
}
public boolean isPng(){
return player.isPlaying();
}
public void pausePlayer(){
player.pause();
}
public void seek(int posn){
player.seekTo(posn);
}
public void go(){
player.start();
}
//skip to previous track
public void playPrev(){
songPosn--;
if(songPosn<0) songPosn=songs.size()-1;
playSong();
}
//skip to next
public void playNext(){
if(shuffle){
int newSong = songPosn;
while(newSong==songPosn){
newSong=rand.nextInt(songs.size());
}
songPosn=newSong;
}
else{
songPosn++;
if(songPosn>=songs.size()) songPosn=0;
}
playSong();
}
#Override
public void onDestroy() {
stopForeground(true);
}
//toggle shuffle
public void setShuffle(){
if(shuffle) shuffle=false;
else shuffle=true;
}
}
OR
if you want to learn from scratch then
follow this link to learn and create your self too.
http://code.tutsplus.com/tutorials/create-a-music-player-on-android-project-setup--mobile-22764
http://code.tutsplus.com/tutorials/create-a-music-player-on-android-song-playback--mobile-22778
http://code.tutsplus.com/tutorials/create-a-music-player-on-android-user-controls--mobile-22787
i hope it helps you.
thanks.

Service Intent must be explicit

I'm trying to use service for a background music.
package com.example.neotavraham;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class PlayMusicService extends Service implements MediaPlayer.OnPreparedListener {
public static final String ACTION_PLAY = "com.example.neotavraham.PLAY";
MediaPlayer mMediaPlayer = null;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = MediaPlayer.create(this, R.raw.yedid_nefesh);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
return flags;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I call it from the MainActivity with the line: startService(new Intent(PlayMusicService.ACTION_PLAY));
and of course I added an intent-filter
<intent-filter>
<action android:name="com.example.neotavraham.PLAY"/>
</intent-filter>
I was looking for a fine solution in the internet but couldn't find one...what should I do?
Please call the service from intent and set the action of that intent like this:
Intent i = new Intent(this,PlayMusicService.class);
i.setAction("com.example.neotavraham.PLAY");
startService(i);
This code will work.
Background service for start media player
package com.example.neotavraham;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class PlayMusicService extends Service {
public static final String ACTION_PLAY = "com.example.neotavraham.PLAY";
MediaPlayer mMediaPlayer = null;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = MediaPlayer.create(this, R.raw.idil);
mMediaPlayer.setLooping(true); // Set looping
mMediaPlayer.setVolume(100,100);
mMediaPlayer.start();
}
return flags;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
mMediaPlayer.stop();
mMediaPlayer.release();
}
}
Thanks
In your activity do the following:
Intent i = new Intent(this,PlayMusicService.class);
i.putExtra("action","com.example.neotavraham.PLAY");
startService(i);
In your service do the following:
package com.example.neotavraham;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class PlayMusicService extends Service {
public static final String ACTION_PLAY = "com.example.neotavraham.PLAY";
MediaPlayer mMediaPlayer = null;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getStringExtra("action").equals(ACTION_PLAY)) {
mMediaPlayer = MediaPlayer.create(this, R.raw.yedid_nefesh);
mMediaPlayer = MediaPlayer.create(this, R.raw.idil);
mMediaPlayer.setLooping(true); // Set looping
mMediaPlayer.setVolume(100,100);
mMediaPlayer.start();
}
return flags;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
mMediaPlayer.stop();
mMediaPlayer.release();
}
}
In your manifiest do the following:
<service
android:name="com.example.neotavraham.PlayMusicService"
/>
This is the perfect code for your app. Hope this will work finally....

android services - error: service not registered

I am trying to understand bounded services. Below my sample program in which I try to follow http://developer.android.com/guide/components/bound-services.html . The service functions as far as I can play, pause, and stop the audio yet when I switch to another app I get the following Service not registered error.
java.lang.RuntimeException: Unable to stop activity {com.example.dd_services_audio_01/com.example.dd_services_audio_01.MainActivity}: java.lang.IllegalArgumentException: Service not registered: com.example.dd_services_audio_01.MainActivity$1#2afca5d8
09-05 14:04:32.625: E/AndroidRuntime(5810): at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:2451)
09-05 14:04:32.625: E/AndroidRuntime(5810): at android.app.ActivityThread.handleStopActivity(ActivityThread.java:2496)
As the coding seems to follow the documentation example closely I have no clue where things go wrong. I run this app with minSdk level 8. The error happens in MainActivity.onStop at the line
mService.unbindService(mConnection);
Any suggestions to solve this would be great.
Thanks
martin
package com.example.dd_services_audio_01;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.example.dd_services_audio_01.AudioPlayerService.AudioPlayerBinder;
public class MainActivity extends Activity {
private final String TAG = "MainActivity";
AudioPlayerService mService;
boolean mBound = false;
Button mPlay, mPause, mStop;
String audioFile = Environment.getExternalStorageDirectory()
+ "/justdzongsar/DJKR_AboutToGetIt.mp3";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG,"onCreate");
setContentView(R.layout.activity_main);
mPlay = (Button) findViewById(R.id.buttonPlay);
mPause = (Button) findViewById(R.id.buttonPause);
mStop = (Button) findViewById(R.id.buttonStop);
mPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mService.play(audioFile);
}
});
mPause.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mService.pause();
}
});
mStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mService.stop();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, AudioPlayerService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
if (mBound) {
mService.unbindService(mConnection);
mBound=false;
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get
// LocalService instance
AudioPlayerBinder binder = (AudioPlayerBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mService = null;
mBound = false;
}
};
}
and
package com.example.dd_services_audio_01;
import java.io.IOException;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class AudioPlayerService extends Service implements OnPreparedListener,
OnCompletionListener {
private final String TAG = "AudioPlayerService";
private final IBinder mBinder = new AudioPlayerBinder();
private MediaPlayer mMediaPlayer;
private String currentDataSource;
public class AudioPlayerBinder extends Binder {
public AudioPlayerService getService() {
Log.v(TAG, "AudioPlayerBinder: getService() called");
return AudioPlayerService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return false;
}
#Override
public void onStart(Intent intent, int startId) {
Log.i(TAG,
"AudioPlayerService: onStart() called, instance="
+ this.hashCode());
}
#Override
public void onDestroy() {
Log.i(TAG, "AudioPlayerService: onDestroy() called");
releaseMediaPlayer();
}
// -----
public void play(String audioFile) {
Log.d(TAG, "audio play called with file " + audioFile);
if (mMediaPlayer != null && audioFile.compareTo(currentDataSource) == 0) {
if (mMediaPlayer.isPlaying() == true) {
return;
}
mMediaPlayer.start();
return;
}
releaseMediaPlayer();
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(audioFile);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnCompletionListener(this);
currentDataSource = audioFile;
mMediaPlayer.prepareAsync();
} catch (IOException ioe) {
Log.e(TAG, "error trying to play " + audioFile, ioe);
}
}
public void pause() {
Log.d(TAG, "audio pause");
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
}
public void seek(int timeInMillis) {
if (mMediaPlayer != null) {
mMediaPlayer.seekTo(timeInMillis);
}
}
public int elapsed() {
if (mMediaPlayer == null) {
return 0;
}
return mMediaPlayer.getCurrentPosition();
}
public void stop() {
Log.d(TAG, "audio stop");
releaseMediaPlayer();
}
// --
private void releaseMediaPlayer() {
if (mMediaPlayer == null) {
return;
}
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer = null;
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
releaseMediaPlayer();
}
#Override
public void onPrepared(MediaPlayer mp) {
if (mp != null) {
mp.start();
}
// TODO Auto-generated method stub
}
}
Had a similar problem, but the accepted answer was not the solution for me. Luckily one of the comments gave me the answer:
onServiceDisconnected is not supposed to be raised when you unbind your service, so don't rely on it. It is supposed to inform you in case the connection between your Service and ServiceConnection is dropped.
Thanks to #Waqas I found the error: I was updating the boolean binded flag only inside onServiceConnected() and onServiceDisconnected(). Now I've added "binded=false" every time I call unbindService() and the problem has gone. That's it, don't rely on onServiceDisconnected
Ah, one of these days
mService.unbindService(mConnection);
is obviously nonsense, calling unbind in the wrong context. It should be
unbindService(mConnection);
Additional mistake in the posted coding is the missing of
#Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
releaseMediaPlayer();
return false;
}
As a sidenote, since none of the other answers helped, I found that my error was using a different Context for bind and unbind. My bind was from the Application context, but my unbind was from the Activity context.
To fix the error, I made sure to use the same context for bindService() and unbindService().
You may need to ensure that mService is not null. The following line gave me the "Service not Registered" error:
if (mContext != null) mContext.unbindService(mServiceConn);
This was very confusing because both mContext and mServiceConn were not null.
This fixed it:
if (mContext != null && mService != null) mContext.unbindService(mServiceConn);
My MediaPlayer would stop when I killed the app, but 5 minutes layer or less it would start back up again all on its own.
To fix this, in addition to #dorjeduck's answer, I had to also call mediaPlayer.stop() before calling mediaPlayer.release().

MediaPlayer android doesnt play

i use these lines to play some audio file with mediaplayer, both on a service and in an activity, yet there is no sound on my device, what could be the reason? and what should i try to do to understand whats wrong and finally fix that?
MediaPlayer mp = MediaPlayer.create(this, R.raw.alert);
mp.start();
Intent viewMediaIntent = new Intent();
viewMediaIntent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(objectFilePath);
viewMediaIntent.setDataAndType(Uri.fromFile(file), "audio/*");
viewMediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(viewMediaIntent);
http://developer.android.com/reference/android/media/MediaPlayer.html
Check out the state diagram in the MediaPlayer docs.
After you've created the MediaPlayer it is in the Idle state. As you can see, you need to initialize and prepare it before you call start().
Check the following code, it works fine for me. I hope it will work for you also.....Dont forget to add Audio PlayBack permission in android Manifest File
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://android.erkutaras.com/media/audio.mp3";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
}

MediaPlayer's SetOnCompletionListener is not working

m using service to play a audio file in background.
This is my PreviewServices class .
package com.hungama.myplay.activity;
import java.io.IOException;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.MediaController;
import android.widget.Toast;
public class PreviewServices extends Service {
private static final String TAG = "PreviewServices";
public static MediaPlayer player;
protected DataManager dataManager = DataManager.getInstance();
String song_uri, url;
private IBinder myBinder;
private boolean isplaying;
#Override
public IBinder onBind(Intent intent) {
return null;
}
public class MyBinder extends Binder {
PreviewServices getService() {
return PreviewServices.this;
}
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate " + song_uri);
}
#Override
public void onDestroy() {
player.stop();
}
public void onPause() {
player.pause();
}
public double duration() {
return player.getDuration();
}
public void onStart(Intent intent, int startid) {
Bundle b = intent.getExtras();
song_uri = b.getString("song_uri");
Uri path = Uri.parse(song_uri);
player = MediaPlayer.create(this, path);
player.setLooping(false); // Set looping
player.start();
/ *player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Log.d("song is completed","song is not playing now");
dataManager.setPreview_play(true);
}
});
*/
}
}
My PreviewServices is working fine,
in My Activity i want to show a message when my song will complete.
m using this code for this purpose.
PreviewServices preview=new PreviewServices();
MusicScreen.this.preview.player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Log.d("song is complete","song complete");
}
});
I dont know Y its throws Null Pointer Exception in this line
MusicScreen.this.preview.player.setOnCompletionListener(new OnCompletionListener()
please suggest me where is problem.
thanks in advance.
Gaurav Gupta
I'm sure you'll get more responses if your code is displayed properly. Every line of code needs to have four spaces or a tab at the start of it. Try editing to fix it.
A simple thing you can do is break up the line like this (where you specify appropriate classes for x, y and z):
x = MusicScreen.this
y = x.preview
z = y.player
z.setOnCompletionListener(ETC.
Then you can see where it breaks down. Other than that, I don't understand your program so I can't help...

Categories

Resources