// BUTTONS
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
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<HashMap<String, String>> songsList = new
ArrayList<HashMap<String, String>>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab3_soundfragment, container, false);
/**
* Receiving song index from playlist view
* and play the song
* */
#Override
public 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);
}
};
/*
*
*/
#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();
}
/**
* On Song Playing completed
* if repeat is ON play same song again
* if shuffle is ON play random song
* */
#Override
public void onCompletion(MediaPlayer arg0) {
// 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;
}
}
}
Im getting the error java.lang.NullPointerException: Attempt to get length of null array
Im kinda new on Android development, if someone can help me i will apreciate.
Im trying to get musics from url's but when i do this, this give me this error
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;
}
});
Collecting the total duration of an audio has become a problem for me. I am creating an activity that plays an audio from online, I use the android media player. Now the audio is able to play correctly, but the problem I am facing is allowing the seek bar progress accordingly with the audio. The seek bar is set correctly but i have seen that the getDuration returns 0 value.
Below is what i have done.
public class AudioDetails extends AppCompatActivity
implements MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audios_details_activity);
// Mediaplayer
mp = new MediaPlayer();
utils = new AudioUtilities();
// Listeners
songProgressBar.setOnSeekBarChangeListener(this); // Important
mp.setOnCompletionListener(this); // Important
// 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);
}
}
}
});
}
/**
* Function to play a song
* #param songIndex - index of song
* */
public void playSong(int songIndex){
// Play song
try {
mp.reset();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource("http://test.com/test/upload/Twale_FLO.mp3");
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
totalDuration =mp.getDuration();
}
});
} catch (IOException e) {
e.printStackTrace();
}
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(99);
// 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 currentDuration = mp.getCurrentPosition();
long totalDuration = mp.getDuration();
// 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);
}
};
/**
*
* */
#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();
}
/**
* On Song Playing completed
* if repeat is ON play same song again
* if shuffle is ON play random song
* */
#Override
public void onCompletion(MediaPlayer arg0) {
// check for repeat is ON or OFF
if(isRepeat){
// repeat is on play same song again
playSong(currentSongIndex);
} else{
// play first song
playSong(0);
currentSongIndex = 0;
}
}
#Override
public void onDestroy(){
super.onDestroy();
mp.release();
}}
Please how can I get the total duration of the audio file streaming from online via android? Thanks in advance.
There are some problem with this topic.
The getDuration() does not work on all API versions. So, it is not sure when it will work and when not.
The other way around is to extract metadata. Unfortunately, android MediaMetadataRetriever doesn't work with online source. It works only with sd card files.
Fortunately there is a library available that can help us. And i got the duration with that library. So, these are steps.
add compile 'com.github.wseemann:FFmpegMediaMetadataRetriever:1.0.3' to your gradle.build in dependency
Then you can get duration by below code
FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
mmr.setDataSource("http://owatechinnovations.com/test/upload/Twale_FLO.mp3");
mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM);
mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ARTIST);
long duration =Long.parseLong(mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION));
duration=duration/1000;
long minute=duration/(60);
long second=duration-(minute*60);
mmr.release();
your_text_view.setText(minute+":"+second);
I get the result "4:18" 4 mins 18 secs. hope it helps you
When i play song in music player when i press a button i am forwarding the song for certain time,i am implementing this way,but i need when i press and hold the fast forward button wan to move the song means acting as our real music player,how can i am implementing please help me how i implement the fast forward button functionality is same as our music player fast forward button.
public class MainActivity extends Activity implements OnCompletionListener,
SeekBar.OnSeekBarChangeListener {
private ImageButton btnDecreaseSound, btnIncSound, btnReverse, btnPlay, btnForward,
btnPause;
private TextView currenttime, endtime;
private LinearLayout btnRedo, btnDelete;
private SeekBar songProgressBar;
private MediaPlayer mp;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private SeekBar volumeSeekbar ;
private AudioManager audioManager ;
private Handler mHandler = new Handler();
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Mediaplayer
mp = new MediaPlayer();
songManager = new SongsManager();
utils = new Utilities();
final SoundPool spool = null;
final int soundID = 0;
audioManager = (AudioManager) getSystemService(getApplicationContext().AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
// Listeners
songProgressBar.setOnSeekBarChangeListener(this); // Important
mp.setOnCompletionListener(this); // Important
// Getting all songs list
songsList = songManager.getPlayList();
// By default play first song
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.playbtn);
}
} else {
if (mp != null) {
mp.start();
//
btnPlay.setImageResource(R.drawable.pauseiconbtn);
}
}
}
});
volumeSeekbar.setOnSeekBarChangeListener(new 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);
}
});
btnReverse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// get current song position
int currentPosition = mp.getCurrentPosition();
// check if seekBackward time is greater than 0 sec
if (currentPosition - seekBackwardTime >= 0) {
// forward song
mp.seekTo(currentPosition - seekBackwardTime);
} else {
// backward to starting position
mp.seekTo(0);
}
}
});
btnForward.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int currentPosition = mp.getCurrentPosition();
// check if seekForward time is lesser than song duration
if (currentPosition + seekForwardTime <= mp.getDuration()) {
// forward song
mp.seekTo(currentPosition + seekForwardTime);
} else {
// forward to end position
mp.seekTo(mp.getDuration());
}
}
});
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");
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();
}
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// Displaying Total Duration time
// endtime.setText(""+utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
currenttime
.setText("" + utils.milliSecondsToTimer(currentDuration));
//
String l = utils.milliSecondsToTimer(currentDuration);
String l2 = utils.milliSecondsToTimer(currentDuration);
long number = totalDuration - currentDuration;
String timechange = utils.milliSecondsToTimer(number);
System.out.println("l value: " + timechange);
endtime.setText("-" + timechange);
// 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);
}
};
#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();
}
/**
* On Song Playing completed if repeat is ON play same song again if shuffle
* is ON play random song
* */
#Override
public void onCompletion(MediaPlayer arg0) {
// check for repeat is ON or OFF
playSong(0);
currentSongIndex = 0;
}
#Override
public void onDestroy() {
super.onDestroy();
mp.release();
}
you can not override Home button for your custom application. that is reserved. Please google it regarding overriding home button
Please go to this link\, you can get your answer here.
Android Overriding home key
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().