I m having a weird error! A few minutes ago there were no errors then I cleaned up the project and suddenly an error! I recently removed an error : FATAL EXCEPTION: main; Error receiving broadcast Intent ! by commenting
//seekIntent.putExtra("song_ended", "1");
//sendBroadcast(seekIntent);
in myPlayService();
Error :
05-04 02:59:04.074: E/MediaPlayer(22138): start called in state 4
05-04 02:59:04.074: E/MediaPlayer(22138): error (-38, 0)
05-04 02:59:04.075: E/MediaPlayer(22138): Error (-38,0)
myPlayService :(Service file)
public class myPlayService extends Service implements OnCompletionListener,
OnPreparedListener, OnSeekCompleteListener, OnErrorListener {
// Media Player
private MediaPlayer mp;
private int currentSongIndex;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private SongsManager songManager;
// Pausing when phone call
private boolean isPausedInCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
// Declare headsetSwitch variable
private int headsetSwitch = 1;
// ---Variables for seekbar processing---
Intent seekIntent;
String sntSeekPos;
int intSeekPos;
int mediaPosition;
int mediaMax;
private final Handler handler = new Handler();
private int songEnded = 0;
public static final String BROADCAST_ACTION = "com.ayush.mymusicplayer.seekprogress";
public void onCreate() {
// ---Set up intent for seekbar broadcast ---
seekIntent = new Intent(BROADCAST_ACTION);
// Register headset receiver
registerReceiver(headsetReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
songManager = new SongsManager();
songsList = songManager.getPlayList();
mp = new MediaPlayer();
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
mp.setOnSeekCompleteListener(this);
mp.setOnErrorListener(this);
mp.reset();
}
public int onStartCommand(Intent intent, int flags, int startId) {
// ---Set up receiver for State change ---
registerReceiver(broadcastActivityReceiver, new IntentFilter(
MyMainActivity.BROADCASTING));
// ---Set up receiver for seekbar change ---
registerReceiver(broadcastReceiver, new IntentFilter(
MyMainActivity.BROADCAST_SEEKBAR));
// Manage incoming phone calls during playback. Pause mp on incoming,
// resume on hangup.
// -----------------------------------------------------------------------------------
// Get the telephony manager
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mp != null) {
pauseMedia();
isPausedInCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mp != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
// Getting song Index from MyMainActivity
currentSongIndex = intent.getExtras().getInt("currentSongIndex");
mp.reset();
if (!mp.isPlaying()) {
try {
mp.setDataSource(songsList.get(currentSongIndex)
.get("songPath"));
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
// --- Set up seekbar handler ---
setupHandler();
return START_STICKY;
}
// If headset gets unplugged, stop music and service.
private BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
private boolean headsetConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.hasExtra("state")) {
if (headsetConnected && intent.getIntExtra("state", 0) == 0) {
headsetConnected = false;
headsetSwitch = 0;
} else if (!headsetConnected
&& intent.getIntExtra("state", 0) == 1) {
headsetConnected = true;
headsetSwitch = 1;
}
}
switch (headsetSwitch) {
case (0):
pauseMedia();
break;
case (1):
playMedia();
break;
}
}
};
// ---Send seekbar info to activity----
private void setupHandler() {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 250); // 0.25 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
LogMediaPosition();
handler.postDelayed(this, 250); // 0.25 seconds
}
};
private void LogMediaPosition() {
if (mp.isPlaying()) {
mediaPosition = mp.getCurrentPosition();
mediaMax = mp.getDuration();
seekIntent.putExtra("counter", String.valueOf(mediaPosition));
seekIntent.putExtra("mediamax", String.valueOf(mediaMax));
seekIntent.putExtra("song_ended", String.valueOf(songEnded));
sendBroadcast(seekIntent);
}
}
// --Receive seekbar position if it has been changed by the user in the
// activity
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateSeekPos(intent);
}
};
// Update seek position from Activity
public void updateSeekPos(Intent intent) {
int seekPos = intent.getIntExtra("seekpos", 0);
if (mp.isPlaying()) {
handler.removeCallbacks(sendUpdatesToUI);
mp.seekTo(seekPos);
setupHandler();
}
}
// Play Song After Complition !
#Override
public void onSeekComplete(MediaPlayer mp) {
if (!mp.isPlaying()) {
playMedia();
}
}
public void onPrepared(MediaPlayer arg0) {
// Send a message to activity to end progress dialogue
playMedia();
}
// Set up broadcast receiver
private BroadcastReceiver broadcastActivityReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent broadcastIntent) {
String broadcastValue = broadcastIntent
.getStringExtra("Broadcasting");
int broadcastIntValue = Integer.parseInt(broadcastValue);
switch (broadcastIntValue) {
case 0:
pauseMedia();
break;
case 1:
playMedia();
break;
}
}
};
public void pauseMedia() {
if (mp.isPlaying()) {
mp.pause();
}
}
public void playMedia() {
if (!mp.isPlaying()) {
mp.start();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
seekIntent.putExtra("song_ended", "1");
sendBroadcast(seekIntent);
stopSelf();
}
#Override
public void onDestroy() {
super.onDestroy();
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.reset();
mp.release();
}
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_NONE);
}
// Stop the seekbar handler from sending updates to UI
handler.removeCallbacks(sendUpdatesToUI);
unregisterReceiver(headsetReceiver);
// Unregister seekbar receiver
unregisterReceiver(broadcastReceiver);
unregisterReceiver(broadcastActivityReceiver);
stopSelf();
}
// ---Error processing ---
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this,
"MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "MEDIA ERROR SERVER DIED " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "MEDIA ERROR UNKNOWN " + extra,
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
MyMainActivity :
public class MyMainActivity extends Activity implements OnSeekBarChangeListener {
private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnPlaylist;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private SeekBar songProgressBar;
private int seekMax;
private int seekProgress;
private static int songEnded = 0;
boolean mBroadcastIsRegistered;
private int seekPos;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private boolean startedPlaying = false;
private boolean paused = false;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
Intent serviceIntent;
// Broadcasting
Intent broadcastStateIntent;
public static final String BROADCASTING = "com.ayush.mymusicplayer.broadcasting";
// --Set up constant ID for broadcast of seekbar position--
public static final String BROADCAST_SEEKBAR = "com.ayush.mymusicplayer.sendseekbar";
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
try {
// All player buttons
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
btnForward = (ImageButton) findViewById(R.id.btnForward);
btnBackward = (ImageButton) findViewById(R.id.btnBackward);
btnNext = (ImageButton) findViewById(R.id.btnNext);
btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songTitleLabel = (TextView) findViewById(R.id.songTitle);
songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
songManager = new SongsManager();
utils = new Utilities();
// --- set up seekbar intent for broadcasting new position to
// service ---
intent = new Intent(BROADCAST_SEEKBAR);
broadcastStateIntent = new Intent(BROADCASTING);
// songProgressBar.setOnSeekBarChangeListener(this); // Important
serviceIntent = new Intent(this, myPlayService.class);
// Getting all songs list
songsList = songManager.getPlayList();
// set the starting title song
songTitleLabel.setText(songsList.get(0).get("songTitle"));
// registerReceiver(broadcastServiceReceiver, new IntentFilter(
// myPlayService.BROADCASTING_FROM_SERVICE));
// Listeners
songProgressBar.setOnSeekBarChangeListener(this);
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check for already playing
if (startedPlaying == false && paused == false) {
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
playSong(currentSongIndex);
startedPlaying = true;
paused = false;
} else if (startedPlaying == false && paused == true) {
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_pause);
resumingBroadcast();
paused = false;
startedPlaying = true;
}
else if (startedPlaying == true && paused == false) {
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
pausingBroadcast();
paused = true;
startedPlaying = false;
}
}
});
/**
* Forward button click event Forwards song specified seconds
* */
btnForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check if seekForward time is lesser than song duration
if (seekProgress + seekForwardTime <= seekMax) {
// forward song
seekPos = seekProgress + seekForwardTime;
intent.putExtra("seekpos", seekPos);
sendBroadcast(intent);
} else {
// forward to end position
seekPos = seekMax;
intent.putExtra("seekpos", seekPos);
sendBroadcast(intent);
}
}
});
/**
* Backward button click event Backward song to specified seconds
* */
btnBackward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check if seekBackward time is greater than 0 sec
if (seekProgress - seekBackwardTime >= 0) {
// forward song
seekPos = seekProgress + seekBackwardTime;
intent.putExtra("seekpos", seekPos);
sendBroadcast(intent);
} else {
// backward to starting position
intent.putExtra("seekpos", 0);
sendBroadcast(intent);
}
}
});
/**
* Button Click event for Play list click event Launches list
* activity which displays list of songs
* */
btnPlaylist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
PlayListActivity.class);
startActivityForResult(i, 100);
}
});
/**
* Next button click event Plays next song by taking
* currentSongIndex + 1
* */
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else {
// check if next song is there or not
if (currentSongIndex < (songsList.size() - 1)) {
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
playSong(0);
currentSongIndex = 0;
}
}
}
});
/**
* Back button click event Plays previous song by currentSongIndex -
* 1
* */
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else {
if (currentSongIndex > 0) {
playSong(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
} else {
// play last song
playSong(songsList.size() - 1);
currentSongIndex = songsList.size() - 1;
}
}
}
});
/**
* Button Click event for Repeat button Enables repeat flag to true
* */
btnRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isRepeat) {
isRepeat = false;
Toast.makeText(getApplicationContext(),
"Repeat is OFF", Toast.LENGTH_SHORT).show();
btnRepeat.setImageResource(R.drawable.btn_repeat);
} else {
// make repeat to true
isRepeat = true;
Toast.makeText(getApplicationContext(), "Repeat is ON",
Toast.LENGTH_SHORT).show();
// make shuffle to false
isShuffle = false;
btnRepeat
.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}
}
});
/**
* Button Click event for Shuffle button Enables shuffle flag to
* true
* */
btnShuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isShuffle) {
isShuffle = false;
Toast.makeText(getApplicationContext(),
"Shuffle is OFF", Toast.LENGTH_SHORT).show();
btnShuffle.setImageResource(R.drawable.btn_shuffle);
} else {
// make repeat to true
isShuffle = true;
Toast.makeText(getApplicationContext(),
"Shuffle is ON", Toast.LENGTH_SHORT).show();
// make shuffle to false
isRepeat = false;
btnShuffle
.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.btn_repeat);
}
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
/**
* Receiving song index from playlist view and play the song
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
currentSongIndex = data.getExtras().getInt("songIndex");
// play selected song
playSong(currentSongIndex);
}
}
// -- onPause, unregister broadcast receiver. To improve, also save screen data ---
#Override
protected void onPause() {
// Unregister broadcast receiver
if (mBroadcastIsRegistered) {
unregisterReceiver(broadcastReceiver);
mBroadcastIsRegistered = false;
}
super.onPause();
}
// -- onResume register broadcast receiver. To improve, retrieve saved screen data ---
#Override
protected void onResume() {
// Register broadcast receiver
if (!mBroadcastIsRegistered) {
registerReceiver(broadcastReceiver, new IntentFilter(
myPlayService.BROADCAST_ACTION));
mBroadcastIsRegistered = true;
}
super.onResume();
}
// -- Broadcast Receiver to update position of seekbar from service --
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent serviceIntent) {
updateUI(serviceIntent);
}
};
private void updateUI(Intent serviceIntent) {
String counter = serviceIntent.getStringExtra("counter");
String mediamax = serviceIntent.getStringExtra("mediamax");
String strSongEnded = serviceIntent.getStringExtra("song_ended");
seekProgress = Integer.parseInt(counter);
seekMax = Integer.parseInt(mediamax);
songEnded = Integer.parseInt(strSongEnded);
songProgressBar.setMax(seekMax);
songProgressBar.setProgress(seekProgress);
// Displaying Total Duration time
songTotalDurationLabel.setText("" + utils.milliSecondsToTimer(seekMax));
// Displaying time completed playing
songCurrentDurationLabel.setText(""
+ utils.milliSecondsToTimer(seekProgress));
if (songEnded == 1) {
// check for repeat is ON or OFF
if (isRepeat) {
// repeat is on play same song again
playSong(currentSongIndex);
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else {
// no repeat or shuffle ON - play next song
if (currentSongIndex < (songsList.size() - 1)) {
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
playSong(0);
currentSongIndex = 0;
}
}
}
}
// Send a message to Server to pause
private void pausingBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
broadcastStateIntent.putExtra("Broadcasting", "0");
paused = true;
btnPlay.setImageResource(R.drawable.btn_play);
sendBroadcast(broadcastStateIntent);
}
// Send a message to Server to resume
private void resumingBroadcast() {
broadcastStateIntent.putExtra("Broadcasting", "1");
paused = false;
btnPlay.setImageResource(R.drawable.btn_pause);
sendBroadcast(broadcastStateIntent);
}
// Function to play a song
public void playSong(int songIndex) {
stopMyPlayService();
paused = false;
startedPlaying = true;
serviceIntent.putExtra("currentSongIndex", songIndex);
// -- Register receiver for seekbar--
registerReceiver(broadcastReceiver, new IntentFilter(
myPlayService.BROADCAST_ACTION));
mBroadcastIsRegistered = true;
try {
startService(serviceIntent);
// Displaying Song title
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
private void stopMyPlayService() {
// --Unregister broadcastReceiver for seekbar
if (mBroadcastIsRegistered) {
try {
unregisterReceiver(broadcastReceiver);
mBroadcastIsRegistered = false;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(
getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
try {
stopService(serviceIntent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
// --- When user manually moves seekbar, broadcast new position to service
#Override
public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
seekPos = sb.getProgress();
intent.putExtra("seekpos", seekPos);
sendBroadcast(intent);
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
The problem seems to be that you call reset() before calling isPlaying() here:
mp.reset();
if (!mp.isPlaying()) {
according the MediaPlayer documentation after calling reset() the MediaPlayer will move into its uninitialized "idle" state. Then calling isPlaying() on an uninitialized state MediaPlayer will then throw an IllegalStateException.
==> After resetting the Mediaplayer you will need to initialize / prepare it again before you can start it again
Related
Hi am trying to stream online radio while opening my app when buffering first time it runs fine while i close the app and then start again the app it plays from where the player last closed and then stopped after it ends and i have to startup manually to stream the url for current level of radio
my coding:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawer;
ImageView list_activity_check;
ImageView share,speaker,mute, control;
DrawerListAdapter drawerListAdapter;
ListView listview_nav;
private SmallBang mSmallBang;
String [] Items={"Program Lists","Rate app"} ;
int [] images={R.drawable.pro_logo,
R.drawable.rate_icon} ;
String[] titles = {
"Ippadikku Idhayam",
"Akilam 360",
"Cine Pattarai",
"Palsuvai Thoranam",
"Pesum Noolagam",
"Lollu Cafe",
"Kavi Saagaram",
"Aa muthal Akk",
"Thiraicholai",
"Kathamba Saaral",
"Paarkatha Pakkangal",
"Pagadi Panna Porom",
};
public static final String[] fromtime = new String[]{"10:30 AM","12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM"};
public static final String[] totime = new String[]{"12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM","10:30 AM"};
Integer[] images0 = {
R.drawable.ipadikku_idhayam,
R.drawable.akilam_360,
R.drawable.cine_pattarai,
R.drawable.palsuvai_thoranam,
R.drawable.pesum_noolagam,
R.drawable.lollu_cafe,
R.drawable.kavi_saagaram,
R.drawable.aa_muthal_akk,
R.drawable.thiraicholai,
R.drawable.kathamba_saaral,
R.drawable.paarkatha_pakkangal,
R.drawable.pagadi_panna_porom,
};
//************* Current Show ***************//
ListView list,lvshow;
List<Program> rowItems;
int iImageId;
String sTitle,sFrom,sTo ;
SQLiteDatabase db;
ImageView music;
int media1;
int intValue1;
AdapAdapter Adapadapter;
ArrayList<String> iTitle = null;
ArrayList<String> sQuantity = null;
ArrayList<String> sQuantity1 = null;
ArrayList<String> sImageID = null;
//***************************************//
SeekBar seekbar;
AudioManager audioManager;
MediaPlayer media, mediaPlayer;
boolean playPause = false;
boolean intialStage = true;
int intvalue ;
ImageView timer;
private static final int NOTIFICATION_ID = 1;
String URL = "http://streaming.shoutcast.com/MUKILFMRADIO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addNotification();
mSmallBang = SmallBang.attach2Window(this);
list_activity_check = (ImageView) findViewById(R.id.list_view);
share = (ImageView) findViewById(R.id.share);
speaker = (ImageView) findViewById(R.id.speaker);
mute = (ImageView) findViewById(R.id.mute);
control = (ImageView) findViewById(R.id.play);
timer = (ImageView) findViewById(R.id.timer);
//************ Current show ************//
db = this.openOrCreateDatabase("MukilApp",Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS proname(ID INTEGER PRIMARY KEY AUTOINCREMENT,ImageID INTEGER,Title TEXT,FromTiming INTEGER,ToTiming INTEGER);");
rowItems = new ArrayList<Program>();
for (int i = 0; i < titles.length; i++) {
Program item = new Program(images0[i], titles[i],fromtime[i],totime[i]);
rowItems.add(item);
}
db.execSQL("DELETE FROM proname;");
lvshow = (ListView) findViewById(R.id.lvshow);
// listView.setVisibility(View.INVISIBLE);
final ProgramAdapter adapter = new ProgramAdapter(this,rowItems, false);
for (int i = 0; i < adapter.getCount(); i++) {
Program rowItem = (Program) adapter.getItem(i);
iImageId = rowItem.getImageId();
sTitle = rowItem.getTitle();
sFrom = rowItem.getFromtime();
sTo = rowItem.getTotime();
db.execSQL("INSERT INTO proname (ImageID,Title,FromTiming,ToTiming) VALUES(" + iImageId + ",'" + sTitle + "','" + sFrom + "','" + sTo + "');");
}
final Cursor cView = db.rawQuery("SELECT * FROM proname WHERE FromTiming <= time('now', 'localtime')\n" + "" +
"AND ToTiming >= time('now', 'localtime')\n", null);
if (cView.getCount() > 0) {
sImageID = new ArrayList<String>();
iTitle = new ArrayList<String>();
sQuantity = new ArrayList<String>();
sQuantity1 = new ArrayList<String>();
while (cView.moveToNext()) {
sImageID.add(cView.getString(1));
iTitle.add(cView.getString(2));
sQuantity.add(cView.getString(3));
sQuantity1.add(cView.getString(4));
Adapadapter = new AdapAdapter(this, sImageID, iTitle, sQuantity, sQuantity1);
lvshow.setAdapter(Adapadapter);
}
}
//*************************************//
timer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, Timer_Activity.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
// startActivity(slideactivity, bndlanimation);
startActivityForResult(slideactivity, 1001,bndlanimation);
// finish();
}
});
}
});
media = MediaPlayer.create(this,R.raw.mukil_master_jingle);
media.start();
media.setLooping(true);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (intialStage) {
new Player()
.execute(URL);
}
intvalue = mediaPlayer.getAudioSessionId();
control.setBackgroundResource(R.drawable.pause);
control.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (playPause == false) {
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
new Player().cancel(true);
media.stop();
media.reset();
mediaPlayer.reset();
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
media.stop();
playPause = true;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute(URL);
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = false;
}
}
});
speaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speaker.setVisibility(View.INVISIBLE);
mute.setVisibility(View.VISIBLE);
media.setVolume(0, 0);
mediaPlayer.setVolume(0, 0);
speaker.setImageResource(R.drawable.speaker);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
}
});
mute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
speaker.setVisibility(View.VISIBLE);
mute.setVisibility(View.INVISIBLE);
media.setVolume(1, 1);
mediaPlayer.setVolume(1, 1);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false); // hide built-in Title
}
try {
seekbar = (SeekBar) findViewById(R.id.seekbar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
listview_nav = (ListView) findViewById(R.id.listview_nav);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
drawerListAdapter = new DrawerListAdapter(MainActivity.this, Items, images);
listview_nav.setAdapter(drawerListAdapter);
listview_nav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0){
Intent in = new Intent(MainActivity.this,ShowList_Activity.class);
startActivity(in);
}else if(position == 1){
}
}
});
list_activity_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list_activity_check.setImageResource(R.drawable.playlist);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, EqualizerActivity.class);
slideactivity.putExtra("sessionvalue", intvalue);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
startActivity(slideactivity, bndlanimation);
}
});
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
share.setImageResource(R.drawable.share_icon);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm" + " Mukil FM shareApp");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
if(mediaPlayer == null){//check mp
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
if(media==null){//check mp
if(!media.isPlaying()){
media.start();
}
}
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void addNotification() {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mukil)
.setContentTitle("MUKIL FM")
.setContentText("Smartah Kelunga Ungal MukilFm");
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
class Player extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progress;
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
intialStage = true;
playPause = false;
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
mediaPlayer.prepareAsync();
prepared = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.d("IllegarArgument", e.getMessage());
prepared = false;
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progress.isShowing()) {
progress.cancel();
}
Log.d("Prepared", "//" + result);
mediaPlayer.start();
media.stop();
intialStage = false;
}
public Player() {
progress = new ProgressDialog(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
media.start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
String result=data.getStringExtra("result");
if(result.equalsIgnoreCase("STOP")){
onStop();
finish();
}else if(result.equalsIgnoreCase("Do Nothing")){
Toast.makeText(this, "Timer is not set", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStop() {
super.onStop();
if(media != null){
// media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
// mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
MainActivity.this.finish();
mediaPlayer.release();
media.release();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// super.onBackPressed();
}
}
please help me in fixing this issues..
Thank you in advance..
In your onStop() of your activity stop and release the media player.
Place the below code in your onStop():
#Override
public void onStop() {
super.onStop();
if(media != null){
media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
This is the proper way to stop media player.
Hope it helps:)
Main portions of code :
// This is event handler for buttonClick event
void buttonClick(){
if (buttonPlayStop.getText() == getString(R.string.play_str)) {
buttonPlayStop.setText(getString(R.string.pause_str));
try{
mediaPlayer.start();
startPlayProgressUpdater();
}catch (IllegalStateException e) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
mediaPlayer.pause();
mediaPlayer.seekTo(0);
}
}else {
buttonPlayStop.setText(getString(R.string.play_str));
mediaPlayer.pause();
}
These where the errors, pause called in state 8 error (-38, 0) Error (-38,0) start called in state 0 error (-38, 0) Error (-38,0) and the song is not playing.
Media Player has its own life-cycle when you are calling its functions make sure that you are in correct state of the media player
Best method to do is make a media player service and bind to that service in your activity and maintain all media player methods in that service.
http://examples.javacodegeeks.com/android/android-mediaplayer-example/
add these in your player activity
public MusicService musicSrv ;
private boolean musicBound=false;
private ArrayList<Song> songList;
inside oncreate
songList = new ArrayList<Song>();
getSongList();
add this in your actitivity
#Override
protected void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(this, MusicService.class);
this.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
this.startService(playIntent);
}
}
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
songTitleLabel.setText(""+musicSrv.getSongTitle());
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
public void getSongList(){
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
add list in to your activity and in list item click
if(musicSrv.isPlaying()){
if(musicSrv.status()!=null){
musicSrv.pauseSong();
btnPlay.setImageResource(R.drawable.btn_play);
}
}else{
if(musicSrv.status()!=null){
musicSrv.restartSong();
btnPlay.setImageResource(R.drawable.btn_pause);
}
}
add this as a service in your app
public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,MediaPlayer.OnCompletionListener {
private MediaPlayer player;
private ArrayList songs;
private int songPosn;
private final IBinder musicBind = new MusicBinder();
private boolean isRepeat=false;
private boolean isShuffle = false;
private int seekForwardTime = 5000;
private int seekBackwardTime = 5000;
private int currentSongIndex = 0;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return musicBind;
}
public void onCreate(){
super.onCreate();
songPosn=0;
player = new MediaPlayer();
initMusicPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
}
public void initMusicPlayer(){
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<Song> theSongs){
songs=theSongs;
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
public class MusicBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
public void playSong(){
try{
player.reset();
System.out.println(songs);
System.out.println(songs.get(songPosn));
Song playSong = songs.get(songPosn);
long currSong = playSong.getID();
Uri trackUri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
try {
player.prepareAsync();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
public boolean isListNull()
{
if(songs==null)
return true;
else
return false;
}
public void setSong(int songIndex){
songPosn=songIndex;
}
public boolean isPlaying()
{
return player.isPlaying();
}
public void pauseSong()
{
player.pause();
}
public void restartSong()
{
player.start();
}
public String status()
{
if(player != null)
{
return "sdf";
}
else
return null;
}
public long getDuration()
{
return player.getDuration();
}
public long getCurrentPosition()
{
return player.getCurrentPosition();
}
public void seek(int currentPosition)
{
player.seekTo(currentPosition);
}
public MediaPlayer getPlayer()
{
return player;
}
public int getCurrentSongIndex()
{
System.out.println(songPosn);
return songPosn;
}
public String getSongTitle()
{
Song song = songs.get(songPosn);
return song.getTitle();
}
#Override
public void onCompletion(MediaPlayer arg0)
{
if(isRepeat){
setSong(songPosn);
playSong();
} else if(isShuffle){
// shuffle is on - play a random song
Random rand = new Random();
songPosn = rand.nextInt((songs.size() - 1) - 0 + 1) + 0;
setSong(songPosn);
playSong();
} else{
// no repeat or shuffle ON - play next song
if(songPosn < (songs.size() - 1)){
setSong(songPosn + 1);
playSong();
songPosn = songPosn + 1;
}else{
// play first song
setSong(0);
playSong();
songPosn = 0;
}
}
}
public void setRepeatSong(boolean re)
{
isRepeat = re;
}
public void setShuffelSong(boolean sh)
{
isShuffle = sh;
}
public void moveForward()
{
int currentPosition = (int) getCurrentPosition();
if(currentPosition + seekForwardTime <= getDuration()){
seek(currentPosition + seekForwardTime);
}else{
seek((int)getDuration());
}
}
public void moveBackward()
{
int currentPosition = (int) getCurrentPosition();
if(currentPosition - seekBackwardTime >= 0){
seek(currentPosition - seekBackwardTime);
}else{
seek(0);
}
}
public void moveNext()
{
currentSongIndex = getCurrentSongIndex();
if(currentSongIndex < (songs.size() - 1)){
setSong(currentSongIndex + 1);
playSong();
currentSongIndex = currentSongIndex + 1;
}else{
setSong(0);
playSong();
currentSongIndex = 0;
}
}
public void movePrevious()
{
currentSongIndex = getCurrentSongIndex();
if(currentSongIndex > 0){
setSong(currentSongIndex - 1);
playSong();
currentSongIndex = currentSongIndex - 1;
}else{
// play last song
setSong(songs.size() - 1);
playSong();
currentSongIndex = songs.size() - 1;
}
}
}
and these in your manifest
service android:name=".Services.MusicService"
inside application tag
use theses permissions
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
hope this will work for you !
I'm trying to create a Service that will play a music in the background in Android.
But I get an NPE while the service is starting.
Could anyone tell me what I'm doing wrong?
Log cat:
12-28 12:07:19.602: W/System.err(3768): java.lang.IllegalStateException
12-28 12:07:19.722: W/System.err(3768): at android.media.MediaPlayer.prepare(Native Method)
12-28 12:07:19.722: W/System.err(3768): at com.darkovski.quran.myPlayService.playMedia(myPlayService.java:413)
12-28 12:07:19.722: W/System.err(3768): at com.darkovski.quran.myPlayService.onPrepared(myPlayService.java:390)
12-28 12:07:19.722: W/System.err(3768): at android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:1523)
12-28 12:07:19.722: W/System.err(3768): at android.os.Handler.dispatchMessage(Handler.java:99)
12-28 12:07:19.722: W/System.err(3768): at android.os.Looper.loop(Looper.java:137)
12-28 12:07:19.722: W/System.err(3768): at android.app.ActivityThread.main(ActivityThread.java:4441)
12-28 12:07:19.722: W/System.err(3768): at java.lang.reflect.Method.invokeNative(Native Method)
12-28 12:07:19.722: W/System.err(3768): at java.lang.reflect.Method.invoke(Method.java:511)
12-28 12:07:19.722: W/System.err(3768): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-28 12:07:19.722: W/System.err(3768): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-28 12:07:19.722: W/System.err(3768): at dalvik.system.NativeStart.main(Native Method)
My code:
public class myPlayService extends Service implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnSeekCompleteListener,
OnInfoListener, OnBufferingUpdateListener {
private static final String TAG = "TELSERVICE";
private MediaPlayer mediaPlayer = new MediaPlayer();
// songs
private ArrayList<Songs> songs;
private int position;
// Set up the notification ID
private static final int NOTIFICATION_ID = 1;
private boolean isPausedInCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
// ---Variables for seekbar processing---
String sntSeekPos;
int intSeekPos;
int mediaPosition;
int mediaMax;
// Intent intent;
private final Handler handler = new Handler();
private static int songEnded;
public static final String BROADCAST_ACTION = "com.darkovski.quran.seekprogress";
// Set up broadcast identifier and intent
public static final String BROADCAST_BUFFER = "com.darkovski.quran.broadcastbuffer";
Intent bufferIntent;
Intent seekIntent;
// Declare headsetSwitch variable
private int headsetSwitch = 1;
// OnCreate
#Override
public void onCreate() {
Log.v(TAG, "Creating Service");
// android.os.Debug.waitForDebugger();
// Instantiate bufferIntent to communicate with Activity for progress
// dialogue
songs = new ArrayList<Songs>();
bufferIntent = new Intent(BROADCAST_BUFFER);
// ---Set up intent for seekbar broadcast ---
seekIntent = new Intent(BROADCAST_ACTION);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.reset();
// Register headset receiver
registerReceiver(headsetReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// get songs and position
songs = (ArrayList<Songs>) intent.getSerializableExtra("songs");
position = intent.getIntExtra("position", -1);
try {
mediaPlayer.setDataSource(songs.get(position).getLink());
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// ---Set up receiver for seekbar change ---
registerReceiver(broadcastReceiver, new IntentFilter(
Player.BROADCAST_SEEKBAR));
// Manage incoming phone calls during playback. Pause mp on incoming,
// resume on hangup.
// -----------------------------------------------------------------------------------
// Get the telephony manager
Log.v(TAG, "Starting telephony");
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Log.v(TAG, "Starting listener");
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// String stateString = "N/A";
Log.v(TAG, "Starting CallStateChange");
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
// Insert notification start
initNotification();
mediaPlayer.reset();
// Set up the MediaPlayer data source using the strAudioLink value
if (!mediaPlayer.isPlaying()) {
try {
// Send message to Activity to display progress dialogue
sendBufferingBroadcast();
mediaPlayer.setDataSource(songs.get(position).getLink());
;
// Prepare mediaplayer
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
// --- Set up seekbar handler ---
setupHandler();
return START_STICKY;
}
// ---Send seekbar info to activity----
private void setupHandler() {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
// // Log.d(TAG, "entered sendUpdatesToUI");
LogMediaPosition();
handler.postDelayed(this, 1000); // 2 seconds
}
};
private void LogMediaPosition() {
// // Log.d(TAG, "entered LogMediaPosition");
if (mediaPlayer.isPlaying()) {
mediaPosition = mediaPlayer.getCurrentPosition();
// if (mediaPosition < 1) {
// Toast.makeText(this, "Buffering...", Toast.LENGTH_SHORT).show();
// }
mediaMax = mediaPlayer.getDuration();
// seekIntent.putExtra("time", new Date().toLocaleString());
seekIntent.putExtra("counter", String.valueOf(mediaPosition));
seekIntent.putExtra("mediamax", String.valueOf(mediaMax));
seekIntent.putExtra("song_ended", String.valueOf(songEnded));
sendBroadcast(seekIntent);
}
}
// --Receive seekbar position if it has been changed by the user in the
// activity
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateSeekPos(intent);
}
};
// Update seek position from Activity
public void updateSeekPos(Intent intent) {
int seekPos = intent.getIntExtra("seekpos", 0);
if (mediaPlayer.isPlaying()) {
handler.removeCallbacks(sendUpdatesToUI);
mediaPlayer.seekTo(seekPos);
setupHandler();
}
}
// ---End of seekbar code
// If headset gets unplugged, stop music and service.
private BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
private boolean headsetConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Log.v(TAG, "ACTION_HEADSET_PLUG Intent received");
if (intent.hasExtra("state")) {
if (headsetConnected && intent.getIntExtra("state", 0) == 0) {
headsetConnected = false;
headsetSwitch = 0;
// Log.v(TAG, "State = Headset disconnected");
// headsetDisconnected();
} else if (!headsetConnected
&& intent.getIntExtra("state", 0) == 1) {
headsetConnected = true;
headsetSwitch = 1;
// Log.v(TAG, "State = Headset connected");
}
}
switch (headsetSwitch) {
case (0):
headsetDisconnected();
break;
case (1):
break;
}
}
};
private void headsetDisconnected() {
stopMedia();
stopSelf();
}
// --- onDestroy, stop media player and release. Also stop
// phoneStateListener, notification, receivers...---
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_NONE);
}
// Cancel the notification
cancelNotification();
// Unregister headsetReceiver
unregisterReceiver(headsetReceiver);
// Unregister seekbar receiver
unregisterReceiver(broadcastReceiver);
// Stop the seekbar handler from sending updates to UI
handler.removeCallbacks(sendUpdatesToUI);
// Service ends, need to tell activity to display "Play" button
resetButtonPlayStopBroadcast();
}
// Send a message to Activity that audio is being prepared and buffering
// started.
private void sendBufferingBroadcast() {
// Log.v(TAG, "BufferStartedSent");
bufferIntent.putExtra("buffering", "1");
sendBroadcast(bufferIntent);
}
// Send a message to Activity that audio is prepared and ready to start
// playing.
private void sendBufferCompleteBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
bufferIntent.putExtra("buffering", "0");
sendBroadcast(bufferIntent);
}
// Send a message to Activity to reset the play button.
private void resetButtonPlayStopBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
bufferIntent.putExtra("buffering", "2");
sendBroadcast(bufferIntent);
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public boolean onInfo(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onSeekComplete(MediaPlayer mp) {
if (!mediaPlayer.isPlaying()) {
playMedia();
Toast.makeText(this, "SeekComplete", Toast.LENGTH_SHORT).show();
}
}
// ---Error processing ---
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this,
"MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "MEDIA ERROR SERVER DIED " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "MEDIA ERROR UNKNOWN " + extra,
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public void onPrepared(MediaPlayer arg0) {
// Send a message to activity to end progress dialogue
sendBufferCompleteBroadcast();
playMedia();
}
#Override
public void onCompletion(MediaPlayer mp) {
// When song ends, need to tell activity to display "Play" button
position += 1;
stopMedia();
playMedia();
// stopSelf();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void playMedia() {
if (!mediaPlayer.isPlaying()) {
try {
//line 413
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Add for Telephony Manager
public void pauseMedia() {
// Log.v(TAG, "Pause Media");
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
public void stopMedia() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
// Create Notification
private void initNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Tutorial: Music In Service";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags = Notification.FLAG_ONGOING_EVENT;
Context context = getApplicationContext();
CharSequence contentTitle = "Music In Service App Tutorial";
CharSequence contentText = "Listen To Music While Performing Other Tasks";
Intent notificationIntent = new Intent(this, Player.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
// Cancel Notification
private void cancelNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
Can anyone tell me what I'm doing wrong?
First, that's not an NPE (null pointer exception).
Second, you are calling your playMedia method entirely too often. Considering that it calls MediaPlayer.prepare, it doesn't make sense in several of the places I see it being called. In particular, you are calling it in the onPrepared callback. The MediaPlayer's state machine is giving you an IllegalStateException because you can't call prepare from the prepared state. You should also not call prepare from the onCompletion callback. The MediaPlayer has a strict state machine and you should probably pay more attention to it.
This is my main activity which is actually a tab activity. I am choosing list of song and i am trying to play radio in activity given below.
public class MainActivity extends TabActivity {
String[] actions = new String[] { "Tune-Up", "About Us", "Like-Us",
"Other", "Exit" };
Spinner country_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
TabHost tabHost = getTabHost();
TabSpec allcallspec = tabHost.newTabSpec("listner");
allcallspec.setIndicator("listener");
Intent allIntent = new Intent(this, Tab_Listner.class);
allcallspec.setContent(allIntent);
// Tab for recived call
TabSpec recivespec = tabHost.newTabSpec("Like");
// setting Title and Icon for the Tab
recivespec.setIndicator("Like");
Intent reciveIntent = new Intent(MainActivity.this, Tab_Like.class);
recivespec.setContent(reciveIntent);
TabSpec recivespec1 = tabHost.newTabSpec("Categery");
// setting Title and Icon for the Tab
recivespec1.setIndicator("CateGories");
Intent reciveIntent1 = new Intent(MainActivity.this,
Category_name.class);
recivespec1.setContent(reciveIntent1);
tabHost.addTab(recivespec);
tabHost.addTab(allcallspec); // Adding photos tab
// Adding songs tab
tabHost.addTab(recivespec1); // Adding songs tab
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// MenuItem mainMenuSpinner = menu.findItem( R.id.menu_main_spinner);
// setupMainMenuSpinner( mainMenuSpinner );
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", "" + currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ActionBar actionBar = getActionBar();
getMenuInflater().inflate(R.menu.mainactivity, menu);
Log.i("Android Version is", "Belove Froyo Action Bar Not Displayed");
MenuItem statusSpinner = menu.findItem(R.id.menu_status_spinner);
setupStatusSpinner(statusSpinner);
}
return super.onCreateOptionsMenu(menu);
}
private void setupStatusSpinner(MenuItem item) {
View view = item.getActionView();
if (view instanceof Spinner) {
Spinner spinner = (Spinner) view;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
android.R.layout.simple_spinner_dropdown_item, actions);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
switch (arg2) {
case 1:
Log.i("About US", "Go");
startActivity(new Intent(MainActivity.this,
About_Us.class));
break;
case 2:
String url = "https://www.facebook.com/musicbreeds";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
break;
case 3:
Log.i("Other", "Go");
startActivity(new Intent(MainActivity.this, Other.class));
break;
case 4:
Log.i("Exit", "unSuccess");
System.out.print("not.......................");
System.exit(0);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
TextView tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
tv_radio_name.setText(Tab_Listner.name);
}
}
Play_Radio activity, In this activity i play and pause songs. i want to have play/pause button at bottom in my MainActivity to stop and play current song.
public class Play_Radio extends Activity {
private ImageView playButton;
private TextView textStreamed, tv_radio_name, tv_radio_cat;
private boolean isPlaying;
private static StreamingMediaPlayer audioStreamer;
private AudioManager audioManager = null;
ImageView iv_like;
Dialog rankDialog;
RatingBar ratingBar, pre_rating;
float cus_rating;
AdView adView;
Dialog dialog;
public static String name, rating, like, radio_url, id, listner, image;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.play_radio);
if (audioStreamer != null) {
try {
Log.i("Already ply", "Succss");
audioStreamer.stop();
} catch (Exception e) {
}
} else {
Log.i("First time", "Play");
}
initControls();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i("On Pause is call", "Succcess");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", "" + currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
getMenuInflater().inflate(R.menu.main, menu);
Log.i("Android Device above", "Home Enbled");
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.i("Home", "Press");
return true;
}
return super.onOptionsItemSelected(item);
}
private void initControls() {
iv_like = (ImageView) findViewById(R.id.iv_activity_like);
iv_like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v1.vibrate(40);
Toast.makeText(getApplicationContext(),
"Thanks For like Our Station", Toast.LENGTH_LONG)
.show();
}
});
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
textStreamed = (TextView) findViewById(R.id.text_kb_streamed);
playButton = (ImageView) findViewById(R.id.imageView1);
playButton.setEnabled(false);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.i("Click sadg ", "success");
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v1.vibrate(40);
if (audioStreamer.getMediaPlayer().isPlaying()) {
Log.i("play ", "success");
audioStreamer.getMediaPlayer().pause();
playButton.setImageResource(R.drawable.play_radio_play);
} else {
Log.i("pause", "success");
audioStreamer.getMediaPlayer().start();
audioStreamer.startPlayProgressUpdater();
playButton.setImageResource(R.drawable.play_radio_pause);
}
isPlaying = !isPlaying;
}
});
// rating radio sation
ImageView rankBtn = (ImageView) findViewById(R.id.iv_activity_rating);
rankBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rankDialog = new Dialog(Play_Radio.this,
R.style.FullHeightDialog);
rankDialog.setContentView(R.layout.rating_bar);
rankDialog.setCancelable(true);
ratingBar = (RatingBar) rankDialog
.findViewById(R.id.dialog_ratingbar);
float userRankValue = 0;
// ratingBar.setRating(userRankValue);
ratingBar
.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromUser) {
// TODO Auto-generated method stub
cus_rating = rating;
}
});
Button updateButton = (Button) rankDialog
.findViewById(R.id.rank_dialog_button);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Play_Radio.this,
"Thanks For Rating Our Stations",
Toast.LENGTH_LONG).show();
rankDialog.dismiss();
}
});
// now that the dialog is set up, it's time to show it
rankDialog.show();
}
});
String urlstring2 = Tab_Listner.radio_url;
Toast.makeText(Play_Radio.this, "Please Wait...", Toast.LENGTH_LONG)
.show();
startStreamingAudio(urlstring2);
tv_radio_cat = (TextView) findViewById(R.id.tv_play_radio_cat);
tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
tv_radio_name.setText(Tab_Listner.name);
pre_rating = (RatingBar) findViewById(R.id.ratingBar1);
pre_rating.setRating(Float.parseFloat(Tab_Listner.rating));
}
private void startStreamingAudio(String urlstring) {
try {
dialog = new Dialog(Play_Radio.this,
android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.progress_layout);
dialog.setTitle("loading...");
dialog.show();
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
if (audioStreamer != null) {
audioStreamer.interrupt();
}
audioStreamer = new StreamingMediaPlayer(this, textStreamed,
playButton, progressBar, dialog);
audioStreamer.startStreaming(urlstring, 5208, 216);
} catch (Exception e) {
Log.e(getClass().getName(), "Error starting to stream audio.", e);
}
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = { R.drawable.calculator, R.drawable.calendar,
R.drawable.camera };
private Integer[] mImageIds = { R.drawable.calculator, R.drawable.calendar,
R.drawable.camera };
}
i have already add play/pause button in playradio activity and its work but i want to play pause button on mainactivity for start and stop play song which are already play run in to radio activity
public class StreamingMediaPlayer {
private static final int INTIAL_KB_BUFFER = 96 * 10 / 8;// assume
// 96kbps*10secs/8bits
// per byte
private TextView textStreamed;
private ImageView playButton;
private Dialog dialog;
private ProgressBar progressBar;
// Track for display by progressBar
private long mediaLengthInKb, mediaLengthInSeconds;
private int totalKbRead = 0;
// Create Handler to call View updates on the main UI thread.
private final Handler handler = new Handler();
private MediaPlayer mediaPlayer;
private File downloadingMediaFile;
private boolean isInterrupted;
private Context context;
private int counter = 0;
public StreamingMediaPlayer(Context context, TextView textStreamed,
ImageView playButton, ProgressBar progressBar, Dialog dialog) {
this.context = context;
this.textStreamed = textStreamed;
this.playButton = playButton;
this.progressBar = progressBar;
this.dialog = dialog;
}
public void startStreaming(final String mediaUrl, long mediaLengthInKb,
long mediaLengthInSeconds) throws IOException {
this.mediaLengthInKb = mediaLengthInKb;
this.mediaLengthInSeconds = mediaLengthInSeconds;
Runnable r = new Runnable() {
public void run() {
// Dialog dialog=null;
try {
downloadAudioIncrement(mediaUrl);
} catch (IOException e) {
Log.e(getClass().getName(),
"Unable to initialize the MediaPlayer for fileUrl="
+ mediaUrl, e);
return;
}
}
};
new Thread(r).start();
}
public void downloadAudioIncrement(String mediaUrl) throws IOException {
URLConnection cn = new URL(mediaUrl).openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null) {
Log.e(getClass().getName(),
"Unable to create InputStream for mediaUrl:" + mediaUrl);
}
downloadingMediaFile = new File(context.getCacheDir(),
"downloadingMedia.dat");
if (downloadingMediaFile.exists()) {
downloadingMediaFile.delete();
}
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
totalKbRead = totalBytesRead / 1000;
testMediaBuffer();
fireDataLoadUpdate();
} while (validateNotInterrupted());
stream.close();
if (validateNotInterrupted()) {
fireDataFullyLoaded();
}
}
private boolean validateNotInterrupted() {
if (isInterrupted) {
if (mediaPlayer != null) {
mediaPlayer.pause();
// mediaPlayer.release();
}
return false;
} else {
return true;
}
}
private void testMediaBuffer() {
Runnable updater = new Runnable() {
public void run() {
if (mediaPlayer == null) {
// Only create the MediaPlayer once we have the minimum
// buffered data
if (totalKbRead >= INTIAL_KB_BUFFER) {
try {
startMediaPlayer();
} catch (Exception e) {
Log.e(getClass().getName(),
"Error copying buffered conent.", e);
}
}
} else if (mediaPlayer.getDuration()
- mediaPlayer.getCurrentPosition() <= 1000) {
transferBufferToMediaPlayer();
}
}
};
handler.post(updater);
}
private void startMediaPlayer() {
try {
File bufferedFile = new File(context.getCacheDir(), "playingMedia"
+ (counter++) + ".dat");
moveFile(downloadingMediaFile, bufferedFile);
Log.e(getClass().getName(),
"Buffered File path: " + bufferedFile.getAbsolutePath());
Log.e(getClass().getName(),
"Buffered File length: " + bufferedFile.length() + "");
mediaPlayer = createMediaPlayer(bufferedFile);
// We have pre-loaded enough content and started the MediaPlayer so
// update the buttons & progress meters.
mediaPlayer.start();
startPlayProgressUpdater();
playButton.setEnabled(true);
} catch (IOException e) {
Log.e(getClass().getName(), "Error initializing the MediaPlayer.",
e);
return;
}
}
private MediaPlayer createMediaPlayer(File mediaFile) throws IOException {
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(getClass().getName(), "Error in MediaPlayer: (" + what
+ ") with extra (" + extra + ")");
return false;
}
});
FileInputStream fis = new FileInputStream(mediaFile);
mPlayer.setDataSource(fis.getFD());
mPlayer.prepare();
return mPlayer;
}
private void transferBufferToMediaPlayer() {
try {
// First determine if we need to restart the player after
// transferring data...e.g. perhaps the user pressed pause
boolean wasPlaying = mediaPlayer.isPlaying();
int curPosition = mediaPlayer.getCurrentPosition();
// Copy the currently downloaded content to a new buffered File.
// Store the old File for deleting later.
File oldBufferedFile = new File(context.getCacheDir(),
"playingMedia" + counter + ".dat");
File bufferedFile = new File(context.getCacheDir(), "playingMedia"
+ (counter++) + ".dat");
// This may be the last buffered File so ask that it be delete on
// exit. If it's already deleted, then this won't mean anything. If
// you want to
// keep and track fully downloaded files for later use, write
// caching code and please send me a copy.
bufferedFile.deleteOnExit();
moveFile(downloadingMediaFile, bufferedFile);
mediaPlayer.pause();
mediaPlayer = createMediaPlayer(bufferedFile);
mediaPlayer.seekTo(curPosition);
boolean atEndOfFile = mediaPlayer.getDuration()
- mediaPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile) {
mediaPlayer.start();
}
oldBufferedFile.delete();
} catch (Exception e) {
Log.e(getClass().getName(),
"Error updating to newly loaded content.", e);
}
}
private void fireDataLoadUpdate() {
Runnable updater = new Runnable() {
public void run() {
textStreamed.setText((totalKbRead + "Kb"));
float loadProgress = ((float) totalKbRead / (float) mediaLengthInKb);
progressBar.setSecondaryProgress((int) (loadProgress * 100));
if (dialog != null)
dialog.dismiss();
}
};
handler.post(updater);
}
private void fireDataFullyLoaded() {
Runnable updater = new Runnable() {
public void run() {
transferBufferToMediaPlayer();
// Delete the downloaded File as it's now been transferred to
// the currently playing buffer file.
downloadingMediaFile.delete();
textStreamed
.setText(("Audio full loaded: " + totalKbRead + " Kb read"));
}
};
handler.post(updater);
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void startPlayProgressUpdater() {
float progress = (((float) mediaPlayer.getCurrentPosition() / 1000) / mediaLengthInSeconds);
progressBar.setProgress((int) (progress * 100));
if (dialog != null)
dialog.dismiss();
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
public void interrupt() {
playButton.setEnabled(false);
isInterrupted = true;
validateNotInterrupted();
}
public void moveFile(File oldLocation, File newLocation) throws IOException {
if (oldLocation.exists()) {
BufferedInputStream reader = new BufferedInputStream(
new FileInputStream(oldLocation));
BufferedOutputStream writer = new BufferedOutputStream(
new FileOutputStream(newLocation, false));
try {
// byte[] buff = new byte[8192];
/* changing the size of the buffer */
byte[] buff = new byte[16384];
int numChars;
while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
writer.write(buff, 0, numChars);
}
} catch (IOException ex) {
throw new IOException("IOException when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
} finally {
try {
if (reader != null) {
writer.close();
reader.close();
}
} catch (IOException ex) {
Log.e(getClass().getName(),
"Error closing files when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
}
}
} else {
throw new IOException(
"Old location does not exist when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
}
}
public void change_volume(float vol) {
Log.i("Media Player volume change", "Success" + vol);
mediaPlayer.setVolume(vol, vol);
}
public void stop() {
// TODO Auto-generated method stub
mediaPlayer.stop();
}
public void stoppreviousPlayer() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
// mediaPlayer.release();
}
}
}
you need a Service which is independent to the activity to play the song
public class SongService extends Service {
MediaPlayer mm;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mm = MediaPlayer.create(this, R.raw.mainmenu2);
mm.setLooping(true);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mm.stop();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
mm.start();
}
}
then add this whenever you want to play the song in the service.
startService(new Intent(this, SongService.class));
and to finish it add this:
stopService(new Intent(MainMenu.this,SongService.class));
So when you press the button start the service, and whenever you press the stop button stop it. this is how you can play songs through activities.
First you have to create a raw folder in res folder and paste the song you want to play there.
MainActivity,java======
protected void onCreate(){
MediaPlayer backgroundSong;
backgroundSong = MediaPlayer.create(MainActivity.this, R.raw.your_song_name);
backgroundSong.start();}
#Override
protected void stopSong() {
// TODO Auto-generated method stub
backgroundSong.release();
}
OtherActivity.java
protected void onPause(){
MainActivity ma = new MainActivity();
ma.stopSong();
}
My ProgressBar does not reset after audio is done. It reset after some audio's but not others not sure why. Also would like to make pause icon change to play when audio is done if anyone can help out with that to, that will be great!
Heres code:
public class player1 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound01; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound02; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound03;
// Listeners
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player1.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.pauseicon)
if(mp.isPlaying()){
mp.pause();
ImageButton pauseicon =(ImageButton) findViewById(R.id.pauseicon);
pauseicon.setImageResource(R.drawable.playicon);
} else {
mp.start();
ImageButton pauseicon =(ImageButton) findViewById(R.id.pauseicon);
pauseicon.setImageResource(R.drawable.pauseicon);
}}});
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
First issue:
In the thread "run" method, in the while condition you are saying:
(currentPosition<total)
this way "currentPosition" value will never reach "total" value and your progressbar won't go, you should use "less than or equal":
(currentPosition<=total)
so code will be:
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && mp.isPlaying() && currentPosition<=total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
Second issue:
You can change the ImageButton using "mp.setOnCompletionListener(this)" like this:
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
Set it while initializing the mediaplayer, before mp.start()