I have developed one video player which have to play songs from a list of video songs on demand basis. But whenever I run the app it playing one particular song from the list even after clicking another song from the list. The code are as follows...
MainActivity.java
package com.example.mediaplayerdemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.example.mediaplayerdemo.R;
import android.net.Uri;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.VideoView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
@SuppressWarnings("unused")
public class MainActivity extends Activity implements OnCompletionListener, OnSeekBarChangeListener {
VideoView mv ;
public TextView songTitleLabel,startTimeField,endTimeField;
private Handler mHandler = new Handler();;
private double startTime = 0;
private double finalTime = 0;
private Handler myHandler = new Handler();;
private SeekBar seekbar;
private ImageButton playButton,stopButton;
public static int oneTimeOnly = 0;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
private SongsManager songManager;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private Utilities utils;
ImageView imgFavorite;
private int currentSongIndex = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
reset();
setContentView(R.layout.activity_main);
Button add = (Button) findViewById(R.id.button1);
mv = (VideoView)findViewById(R.id.videoView1);
mv.setOnCompletionListener(this);
startTimeField =(TextView)findViewById(R.id.textView3);
endTimeField =(TextView)findViewById(R.id.textView4);
seekbar = (SeekBar)findViewById(R.id.seekBar1);
playButton = (ImageButton)findViewById(R.id.imageButton1);
stopButton = (ImageButton)findViewById(R.id.imageButton2);
imgFavorite = (ImageView)findViewById(R.id.imageView1);
songTitleLabel = (TextView) findViewById(R.id.textView2);
songManager = new SongsManager();
utils = new Utilities();
seekbar.setOnSeekBarChangeListener(this); // Important
mv.setOnCompletionListener(this);
songsList = songManager.getPlayList();
try {
playSong(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playButton.setEnabled(true);
stopButton.setEnabled(false);
mv.setEnabled(true);
/*Start Camera*/
imgFavorite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
open();
}
});
/*End Camera*/
playButton.setOnClickListener(new ImageButton.OnClickListener(){
@Override
public void onClick(View v) {
//reset();
if(mv.isPlaying()){
if(mv!=null){
mv.pause();
//mp.pause();
setFinalTime(mv.getDuration());
startTime = mv.getCurrentPosition();
playButton.setEnabled(true);
stopButton.setEnabled(false);
}
}
else{
if(mv!=null){
setFinalTime(mv.getDuration());
startTime = mv.getCurrentPosition();
mv.start();
playButton.setEnabled(false);
stopButton.setEnabled(true);
}
}
seekbar.setClickable(true);
seekbar.setProgress((int)startTime);
myHandler.postDelayed(mUpdateTimeTask,100);
}
});
stopButton.setOnClickListener(new ImageButton.OnClickListener(){
@Override
public void onClick(View v) {
mv.stopPlayback();
playButton.setEnabled(true);
stopButton.setEnabled(false);
}});
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(getApplicationContext(), AddingMusicActivity.class);
startActivityForResult(myIntent, 100);
}
});
}
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 100){
currentSongIndex = data.getExtras().getInt("songIndex");
}
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mv.getDuration();
long currentDuration = mv.getCurrentPosition();
startTimeField.setText(""+utils.milliSecondsToTimer(totalDuration));
endTimeField.setText(""+utils.milliSecondsToTimer(currentDuration));
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
seekbar.setProgress(progress);
mHandler.postDelayed(this, 100);
}
};
private void reset() {
// TODO Auto-generated method stub
}
public void open(){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
private void playSong(int songIndex) throws IOException {
try {
mv.setVideoPath(songsList.get(songIndex).get("songPath"));
mv.setOnPreparedListener(null);
mv.start();
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);
//playButton.setImageResource(R.drawable.stop);
seekbar.setProgress(0);
seekbar.setMax(100);
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
@Override
public void onDestroy(){
super.onDestroy();
mv.suspend();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onCompletion(MediaPlayer arg0) {
if(currentSongIndex < (songsList.size() - 1)){
try {
reset();
playSong(currentSongIndex + 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentSongIndex = currentSongIndex + 1;
}else{
// play first song
try {
playSong(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentSongIndex = 0;
}
}
public double getFinalTime() {
return finalTime;
}
public void setFinalTime(double finalTime) {
this.finalTime = finalTime;
}
}
AddingMusicActivity.java
package com.example.mediaplayerdemo;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class AddingMusicActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
SongsManager plm = new SongsManager();
// get all songs from sdcard
this.songsList = plm.getPlayList();
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, songsListData,
R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
R.id.songTitle });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int songIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
setResult(100, in);
// Closing PlayListView
finish();
}
});
}
}
SongsManager.java
package com.example.mediaplayerdemo;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
public class SongsManager {
// SDCard Path
final String MEDIA_PATH = new String("/sdcard/");
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Constructor
public SongsManager(){
}
/**
* Function to read all mp3 and mp4 files from sdcard
* and store the details in ArrayList
* */
public ArrayList<HashMap<String, String>> getPlayList(){
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 and .mp4 extension
* */
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3") || name.endsWith(".mp4") || name.endsWith(".MP4"));
}
}
}
Utilities.java
package com.example.mediaplayerdemo;
public class Utilities {
public String milliSecondsToTimer(long milliseconds){
String finalTimerString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int)( milliseconds / (1000*60*60));
int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
// Add hours if there
if(hours > 0){
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if(seconds < 10){
secondsString = "0" + seconds;
}else{
secondsString = "" + seconds;}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
/**
* Function to get Progress percentage
* @param currentDuration
* @param totalDuration
* */
public int getProgressPercentage(long currentDuration, long totalDuration){
Double percentage = (double) 0;
long currentSeconds = (int) (currentDuration / 1000);
long totalSeconds = (int) (totalDuration / 1000);
// calculating percentage
percentage =(((double)currentSeconds)/totalSeconds)*100;
// return percentage
return percentage.intValue();
}
/**
* Function to change progress to timer
* @param progress -
* @param totalDuration
* returns current duration in milliseconds
* */
public int progressToTimer(int progress, int totalDuration) {
int currentDuration = 0;
totalDuration = (int) (totalDuration / 1000);
currentDuration = (int) ((((double)progress) / 100) * totalDuration);
// return current duration in milliseconds
return currentDuration * 1000;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.mediaplayerdemo.MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<VideoView
android:id="@+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/textView1"
android:onClick="DisplayVideo"
android:src="@drawable/play" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/videoView1"
android:layout_alignTop="@+id/videoView1"
android:layout_toRightOf="@+id/textView1"
android:text="TextView" />
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/videoView1"
android:layout_alignRight="@+id/videoView1"
android:src="@drawable/stop" />
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/imageButton1" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/seekBar1"
android:layout_alignLeft="@+id/videoView1"
android:text="TextView" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView3"
android:layout_alignRight="@+id/videoView1"
android:text="TextView" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignRight="@+id/textView3"
android:layout_alignTop="@+id/textView1"
android:src="@android:drawable/ic_menu_camera" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/videoView1"
android:layout_marginRight="20dp"
android:layout_toLeftOf="@+id/imageButton2"
android:text="Playlist" />
</RelativeLayout>
playlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#242424"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector" />
</LinearLayout>
playlist_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="@drawable/list_selector"
android:padding="5dp">
<TextView
android:id="@+id/songTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16dp"
android:padding="10dp"
android:color="#f3f3f3"/>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mediaplayerdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.CAMERA" />
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".AddingMusicActivity"></activity>
</application>
</manifest>
Kindly help me here.
0 comments:
Post a Comment