**
I am developing an media player streaming app.. While playing song the
seekbar is moving according to the song. But onTouching seek bar it is
not playing from the touched position..
**
My Java Code is As Folows...
public class Player extends Activity implements View.OnTouchListener,MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener {
private ImageButton btnPlay;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
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 SeekBar songProgressBar;
private int mediaFileLengthInMilliseconds;
private final Handler handler = new Handler();
String AudioURL = "http://f23.wapka-files.com/download/9/e/9/1408248_9e9b050b4bea1c48ba6b7329.mp3/bed5656a469655b9f12e/08-Chundari.Penne-Dulquer.Salmaan.mp3";
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
//-=------------------------------------------------------------
final ImageView iv = (ImageView) findViewById(R.id.image);
final String imgURL = "https://i.ytimg.com/vi/NLQHBv6lgXE/maxresdefault.jpg";
new DownLoadImageTask(iv).execute(imgURL);
//---------------------------------------------------
// 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);
btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
songTitleLabel = (TextView) findViewById(R.id.songTitle);
songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songProgressBar.setMax(99); // It means 100% .0-99
songProgressBar.setOnTouchListener(null);
mp = new MediaPlayer();
// Mediaplayer
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnBufferingUpdateListener(null);
mp.setOnCompletionListener(null);
try {
} catch (Exception h) {
Toast.makeText(Player.this, "NO MUSIC HERE...........", Toast.LENGTH_SHORT).show();
}
}
private void primarySeekBarProgressUpdater() {
songProgressBar.setProgress((int) (((float) mp.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This math construction give a percentage of "was playing"/"song length"
if (mp.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
public void clik(View view){
try {
mp.setDataSource(AudioURL); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mp.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mp.getDuration(); // gets the song length in milliseconds from URL
if (!mp.isPlaying()) {
mp.start();
btnPlay.setImageResource(R.drawable.btn_pause);
} else {
mp.pause();
btnPlay.setImageResource(R.drawable.btn_play);
}
primarySeekBarProgressUpdater();
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
songProgressBar.setSecondaryProgress(i);
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mp.stop();
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_MOVE){
// Log.d(TAG, "Moved , process data, Moved to :" + seekBarProgress.getProgress());
songProgressBar.setProgress(songProgressBar.getProgress());
return false;
}
// Log.d(TAG, "Touched , Progress :" + seekBarProgress.getProgress());
return true;
}
}
Please Help.....
Maybe you forgot set the position on the MediaPlayer with seekTo(int) method once the seekbar has moved. For example:
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_MOVE){
songProgressBar.setProgress(songProgressBar.getProgress());
//seek to the position toucehd
mp.seekTo(songProgressBar.getProgress());
return false;
}
// Log.d(TAG, "Touched , Progress :" + seekBarProgress.getProgress());
return true;
}
You are setting the songProgressBar.setMax(99); max to 99 set it to mp total duration then seekbar will seek media player.
Add this line as shown in code
songProgressBar.setMax(mediaFileLengthInMilliseconds);
public void clik(View view){
try {
mp.setDataSource(AudioURL); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mp.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mp.getDuration(); // gets the song length in milliseconds from URL
// Add this line here
songProgressBar.setMax(mediaFileLengthInMilliseconds);
if (!mp.isPlaying()) {
mp.start();
btnPlay.setImageResource(R.drawable.btn_pause);
} else {
mp.pause();
btnPlay.setImageResource(R.drawable.btn_play);
}
primarySeekBarProgressUpdater();
}
Related
I am developing an app with audio player.I want to play audio from url i am doing code but its plays audio from local directory i.e raw folder.I want to play song from single url at a time from play list, how to implement code in doinbackground method to play single file. What change i have to do in following code to play audio from url? Suggest me!
public class RelaxationLvAudioPlayerActivity1 extends Activity implements SeekBar.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 SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
private MediaPlayer mp;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private AudioPlayerManager 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 ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_relaxationlv_audioplayer);
// 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);
// Mediaplayer
mp = new MediaPlayer();
songManager = new AudioPlayerManager();
utils = new Utilities();
// Listeners
songProgressBar.setOnSeekBarChangeListener(this); // Important
// Getting all songs list
songsList = songManager.getPlayList();
// By default play first song
playSong(0);
/**
* 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(mp.isPlaying()){
if(mp!=null){
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
}else{
// Resume song
if(mp!=null){
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
}
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// 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(currentSongIndex > 0){
playSong(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
}else{
// play last song
playSong(songsList.size() - 1);
currentSongIndex = songsList.size() - 1;
}
}
});
btnPlaylist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), AudioPlayerListActivity.class);
startActivityForResult(i, 100);
}
});
}
/**
* 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);
}
}
/**
* Function to play a song
* #param songIndex - index of song
* */
public void playSong(int songIndex){
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
// 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);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Update timer on seekbar
* */
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// Displaying Total Duration time
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
/// mHandler.removeCallbacks(mUpdateTimeTask); //add this line
}
};
/**
*
* */
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
/**
* When user starts moving the progress handler
* */
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
mHandler.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
* */
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
#Override
protected void onDestroy() {
if (mUpdateTimeTask != null)
mHandler.removeCallbacks(mUpdateTimeTask );
super.onDestroy();
mp.release();
}
}
public class AudioPlayerManager{
// SDCard Path
// final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath());
final String MEDIA_PATH = "/sdcard/songs/";
// private String MEDIA_PATH =Environment.getExternalStorageDirectory().getPath();
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Constructor
public AudioPlayerManager(){
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
* */
public ArrayList<HashMap<String, String>> getPlayList(){
// File home = new File(MEDIA_PATH);
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which are having .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
}
you can try this
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource("your url");
mp.prepare();
mp.start();
} catch (Exception e) {
// handle exception
}
I am new to android development and currently I'm developing simple music player app. Here question is that how to increase and decrease music player volume when sliding finger up on my main music player activity.
this is my music player fragment
public class Player extends Fragment implements WheelModel.Listener,MediaPlayer.OnCompletionListener,SeekBar.OnSeekBarChangeListener{
private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
public static MediaPlayer mp,mp2;
VisualizerView mVisualizerView;
SliderView sl;
private Visualizer mVisualizer;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
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 ArrayList<SongModel> songsList = new ArrayList<SongModel>();
int songIndex;
AudioManager audioManager;
SongAdapter songAdapter;
public Player(int position) {
songIndex = position;
}
public Player() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.player, container, false);
ClickWheel wheel = (ClickWheel) android.findViewById(R.id.wheel);
wheel.getModel().addListener(this);
return android;
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
btnPlay = (ImageButton)getView().findViewById(R.id.btnPlay);
btnForward = (ImageButton) getView().findViewById(R.id.btnForward);
btnBackward = (ImageButton) getView().findViewById(R.id.btnBackward);
btnNext = (ImageButton) getView().findViewById(R.id.btnNext);
btnPrevious = (ImageButton) getView().findViewById(R.id.btnPrevious);
btnRepeat = (ImageButton) getView().findViewById(R.id.btnRepeat);
btnShuffle = (ImageButton) getView().findViewById(R.id.btnShuffle);
songProgressBar = (SeekBar) getView().findViewById(R.id.songProgressBar);
songTitleLabel = (TextView) getView().findViewById(R.id.songTitle);
songTitleLabel.setSelected(true);
songCurrentDurationLabel = (TextView) getView().findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView) getView().findViewById(R.id.songTotalDurationLabel);
mp = new MediaPlayer();
songManager = new SongsManager();
utils = new Utilities();
songProgressBar.setOnSeekBarChangeListener(this);
mp.setOnCompletionListener(this);
songsList = songManager.getPlayList();
if (songIndex == 0) {
playSong(0);
} else {
playSong(songIndex);
}
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check for already playing
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
btnPlay.setImageResource(R.drawable.btn_pause);
}
}
}
});
btnForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int currentPosition = mp.getCurrentPosition();
if(currentPosition + seekForwardTime <= mp.getDuration()){
mp.seekTo(currentPosition + seekForwardTime);
}else{
mp.seekTo(mp.getDuration());
}
}
});
btnBackward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int currentPosition = mp.getCurrentPosition();
if(currentPosition - seekBackwardTime >= 0){
mp.seekTo(currentPosition - seekBackwardTime);
}else{
mp.seekTo(0);
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(currentSongIndex < (songsList.size() - 1)){
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
playSong(0);
currentSongIndex = 0;
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(currentSongIndex > 0){
playSong(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
}else{
playSong(songsList.size() - 1);
currentSongIndex = songsList.size() - 1;
}
}
});
btnRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(isRepeat){
isRepeat = false;
Toast.makeText(getActivity().getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
btnRepeat.setImageResource(R.drawable.btn_repeat);
}else{
isRepeat = true;
Toast.makeText(getActivity().getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
isShuffle = false;
btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}
}
});
btnShuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(isShuffle){
isShuffle = false;
Toast.makeText(getActivity().getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}else{
isShuffle= true;
Toast.makeText(getActivity().getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
isRepeat = false;
btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.btn_repeat);
}
}
});
}
public void playSong(int songIndex) {
try {
Log.e("playSong()...", "....is called");
mp.reset();
mp.setDataSource(songsList.get(songIndex).getSongPath());
mp.prepare();
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
String songTitle = songsList.get(songIndex).getSongTitle();
songTitleLabel.setText(songTitle);
btnPlay.setImageResource(R.drawable.btn_pause);
mp.start();
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("song...songIndex...", "..." + songIndex);
mHandler.removeCallbacks(mUpdateTimeTask);
if(resultCode == 100){
currentSongIndex = data.getExtras().getInt("songIndex");
// play selected song
playSong(currentSongIndex);
}
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
songCurrentDurationLabel.setText("" + utils.milliSecondsToTimer(currentDuration));
int progress =(int)(utils.getProgressPercentage(currentDuration, totalDuration));
songProgressBar.setProgress(progress);
mHandler.postDelayed(this, 100);
}
};
private void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
#Override
public void onCompletion(MediaPlayer mp) {
if(isRepeat){
playSong(currentSongIndex);
} else if(isShuffle){
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else{
if(currentSongIndex < (songsList.size() - 1)){
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
playSong(0);
currentSongIndex = 0;
}
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
mp.seekTo(currentPosition);
updateProgressBar();
}
#Override
public void onDialPositionChanged(WheelModel sender, int nicksChanged) {
getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
mp2 =MediaPlayer.create(getActivity(),R.raw.djlazer);
mp2.start();
}}
If anyone know the logic of these please help me for this.
thanks in advance...
The event when user releases his finger is MotionEvent.ACTION_UP. I'm not aware if there are any guidelines which prohibit using View.OnTouchListener instead of onClick(), most probably it depends of situation.
Here's my sample working code:
imageButton.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
// Do what you want
return true;
}
return false;
}
});
here's my code below.
I have a meidaplayer in my app. if the user play the music then leave the activity all things are right, but when the user leave the activity without playing the music it cause the force close.
what's the problem?
public class Elementary1Activity extends Activity implements Runnable, OnClickListener, OnSeekBarChangeListener{
private SeekBar seekBar;
private ImageButton startMedia;
private ImageButton pauseMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.elementary1);
TextView title1 = (TextView) findViewById(R.id.title1);
TextView tx1 = (TextView) findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(getAssets(), "font.ttf");
title1.setTypeface(font);
tx1.setTypeface(font);
AudioControl();
}
public void AudioControl(){
seekBar = (SeekBar) findViewById(R.id.seekBarnew2);
startMedia = (ImageButton) findViewById(R.id.playbuttonnew2);
pauseMedia = (ImageButton) findViewById(R.id.pausebuttonnew2);
seekBar.setOnSeekBarChangeListener(this);
startMedia.setOnClickListener(this);
pauseMedia.setOnClickListener(this);
}
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;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
pauseMedia.setVisibility(View.VISIBLE);
seekBar.setVisibility(View.VISIBLE);
startMedia.setVisibility(View.INVISIBLE);
if (v.equals(startMedia)) {
if (mp != null && mp.isPlaying()) return;
if(seekBar.getProgress() > 0) {
mp.start();
return;
}
mp = MediaPlayer.create(Elementary1Activity.this, R.raw.e1);
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
if (v.equals(pauseMedia) && mp!=null) {
mp.pause();
pauseMedia.setVisibility(View.INVISIBLE);
startMedia.setVisibility(View.VISIBLE);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
public void onStop() {
super.onStop();
mp.stop();
}
}
As far as I can read Your code wright, If the user leaves Your Activity, that means the user uses the back button or do something else that makes the app stop, right? If yes, I think the problem is, that You don´t initialize Your MediaPlayer at this time. You are first initializing this MediaPlayer on Button Click, but in onStop() You are stopping a not initialized MediaPlayer. Initialize Your MediaPlayer in onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.elementary1);
TextView title1 = (TextView) findViewById(R.id.title1);
TextView tx1 = (TextView) findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(getAssets(), "font.ttf");
title1.setTypeface(font);
tx1.setTypeface(font);
mp = MediaPlayer.create(Elementary1Activity.this, R.raw.e1);
AudioControl();
}
I haven´t tested Your code, but if this doesn´t work there is still another error, which I hadn´t search for. But this is definitely wrong.
I've got it set up with a random sound playing onCreate and I have to add a seekbar to track the audio, it moves with track but will not go back if seekbar is pulled back to another part in the audio. Any help would be great, only beginner, sorry for being a noob :).
public class player1 extends Activity implements Runnable {
private MediaPlayer mp;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private SeekBar songProgressBar;
private ImageButton playicon;
private ImageButton pauseicon;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private SeekBar seek;
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);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
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();
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.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;
}
songProgressBar.setProgress(currentPosition);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
The run() method is never called. Instead create a Handler object in the main thread (you did already but it is unused), remove the Thread.sleep() from the run method but add a call to postDelayed() method of the Handler at the end of run() (and maybe a condition to call it only while playing).
After starting playback, call run() method once (from main thread). It will then take care about calling itself subsequently with postDelayed().
I'm trying to create something where a single audio file is played and can be paused and manipulated with a progress/seek bar. I want to have an image taking up most of the screen and then a play pause button on the bottom left and the bar to the right of the button. Everything works the seekbar which isn't link to the audio. My progress bar coding is a probably a mess because if taken it from several i've seen on the internet but they are mostly confusing for me as they are for music player apps not for playing a single audio file.
Could someone please help me with the progress bar? Any other tips on improving my programming would be great too.
(I am very new to android and programming just to warn you)
This is my Java:
MediaPlayer mediaPlayer;
Button buttonPlayPause;
ImageView Image;
SeekBar seekBar;
private int stateMediaPlayer;
private final int stateMP_NotStarter = 0;
private final int stateMP_Playing = 1;
private final int stateMP_Pausing = 2;
int total;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playerwere);
Image = (ImageView) findViewById(R.id.pdfview);
Image.setImageResource(R.drawable.wereim);
seekBar = (SeekBar) findViewById(R.id.seekBar);
buttonPlayPause = (Button) findViewById(R.id.playpause);
buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);
seekBar.setOnSeekBarChangeListener(seekBarOnSeekListener);
initMediaPlayer();
Thread currentThread = new Thread(this);
currentThread.start();
}
private void initMediaPlayer() {
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
stateMediaPlayer = stateMP_NotStarter;
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
total = mediaPlayer.getDuration();
}
});
seekBar.setProgress(0);
seekBar.setMax(total);
}
Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (stateMediaPlayer) {
case stateMP_NotStarter:
mediaPlayer.start();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
case stateMP_Playing:
mediaPlayer.pause();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_play);
stateMediaPlayer = stateMP_Pausing;
break;
case stateMP_Pausing:
mediaPlayer.start();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
}
}
};
SeekBar.OnSeekBarChangeListener seekBarOnSeekListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
};
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
}
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(Message msg) {
seekBar.setProgress(msg.what);
}
};
And this is what my java was before i tried to use the seekBar:
MediaPlayer mediaPlayer;
Button buttonPlayPause;
ImageView Image;
private int stateMediaPlayer;
private final int stateMP_NotStarter = 0;
private final int stateMP_Playing = 1;
private final int stateMP_Pausing = 2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playerwere);
Image = (ImageView) findViewById(R.id.pdfview);
Image.setImageResource(R.drawable.wereim);
buttonPlayPause = (Button) findViewById(R.id.playpause);
buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);
initMediaPlayer();
}
private void initMediaPlayer() {
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
stateMediaPlayer = stateMP_NotStarter;
}
Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (stateMediaPlayer) {
case stateMP_NotStarter:
mediaPlayer.start();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
case stateMP_Playing:
mediaPlayer.pause();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_play);
stateMediaPlayer = stateMP_Pausing;
break;
case stateMP_Pausing:
mediaPlayer.start();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
}
}
};
This is my java after Vishal Vaja's answer:
MediaPlayer mediaPlayer;
Button buttonPlayPause;
ImageView Image;
SeekBar seekBar;
Handler handler;
private int stateMediaPlayer;
private final int stateMP_NotStarter = 0;
private final int stateMP_Playing = 1;
private final int stateMP_Pausing = 2;
private int mediaPos;
private int mediaMax;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playerwere);
Image = (ImageView) findViewById(R.id.pdfview);
Image.setImageResource(R.drawable.wereim);
seekBar = (SeekBar) findViewById(R.id.seekBar);
buttonPlayPause = (Button) findViewById(R.id.playpause);
buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);
seekBar.setOnSeekBarChangeListener(seekBarOnSeekChangeListener);
initMediaPlayer();
}
private void initMediaPlayer() {
handler = new Handler();
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
stateMediaPlayer = stateMP_NotStarter;
mediaPos = mediaPlayer.getCurrentPosition();
mediaMax = mediaPlayer.getDuration();
seekBar.setMax(mediaMax); // Set the Maximum range of the
// seekBar.setProgress(mediaPos);// set
// current progress to song's
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100);
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if (mediaPlayer.isPlaying()) {
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
seekBar.setMax(mediaMax_new);
seekBar.setProgress(mediaPos_new);
handler.postDelayed(this, 100); // Looping the thread after 0.1
// second
// seconds
}
}
};
Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (stateMediaPlayer) {
case stateMP_NotStarter:
mediaPlayer.start();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
case stateMP_Playing:
mediaPlayer.pause();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_play);
stateMediaPlayer = stateMP_Pausing;
break;
case stateMP_Pausing:
mediaPlayer.start();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
}
}
};
SeekBar.OnSeekBarChangeListener seekBarOnSeekChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
};
I think this can be work for you.
Create one thread that will check song position and will move seekbar like this,
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if(mediaPlayer.isplaying){
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
seekBar.setMax(mediaMax_new);
seekBar.setProgress(mediaPos_new);
handler.postDelayed(this, 100); //Looping the thread after 0.1 second
// seconds
}
}
};
And call that thread like this,
mediaPos = mediaPlayer.getCurrentPosition();
mediaMax = mediaPlayer.getDuration();
seekBar.setMax(mediaMax); // Set the Maximum range of the
seekBar.setProgress(mediaPos);// set current progress to song's
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100);
public class DetailMusic extends Activity implements View.OnClickListener {
SeekBar seek_bar;
Button play_button, pause_button;
TextView text_shown;
Handler seekHandler = new Handler();
Bundle bundle = new Bundle();
String Musicnames;
int mediaMax;
int mediaPos = 0;
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailmusic);
bundle = getIntent().getExtras();
if (bundle != null) {
Musicnames = bundle.getString("musicnbames");
System.out.println("++++++++++++++++++++++++++++++++" + Musicnames);
Log.e("musicfoldername", Musicnames);
}
seek_bar = (SeekBar) findViewById(R.id.seek_bar);
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
text_shown = (TextView) findViewById(R.id.text_shown);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
//seekUpdation();
String PATH_TO_FILE = Musicnames;
// MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
} catch (IOException e) {
}
mp.start();
seek_bar.setMax(mp.getDuration());
try {
mp.setDataSource(Musicnames);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPos = mp.getCurrentPosition();
mediaMax = mp.getDuration();
seek_bar.setMax(mediaMax); // Set the Maximum range of the
seek_bar.setProgress(mediaPos);// set current progress to song's
seekHandler.removeCallbacks(moveSeekBarThread);
seekHandler.postDelayed(moveSeekBarThread, 100); //cal the thread after 100 milliseconds
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if (mp.isPlaying()) {
int mediaPos_new = mp.getCurrentPosition();
int mediaMax_new = mp.getDuration();
seek_bar.setMax(mediaMax_new);
seek_bar.setProgress(mediaPos_new);
seekHandler.postDelayed(this, 100); //Looping the thread after 0.1 second
}
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
mp.reset();
// mp.start();
text_shown.setText("Playing...");
break;
case R.id.pause_button:
mp.pause();
text_shown.setText("Paused...");
}
}
}