Advertisement
Guest User

Untitled

a guest
May 3rd, 2016
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.08 KB | None | 0 0
  1.  
  2. public class AndroidBuildingMusicPlayerActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {
  3. private ImageButton btnPlay;
  4. public ArrayList<Model> mSurrahList;
  5. public Context mContext;
  6. public ListView listView;
  7. public TextView tvomorTitle;
  8. private ImageButton btnForward;
  9. private ImageButton btnBackward;
  10. private ImageButton btnNext;
  11. private ImageButton btnPrevious;
  12. private SeekBar songProgressBar;
  13. private TextView songTitleLabel;
  14. private TextView songCurrentDurationLabel;
  15. private TextView songTotalDurationLabel;
  16. private FancyAdapter mFancyAdapter;
  17. // Media Player
  18. private MediaPlayer mp;
  19. // Handler to update UI timer, progress bar etc,.
  20. private Handler mHandler = new Handler();
  21. private Utilities utils;
  22. private int seekForwardTime = 5000; // 5000 milliseconds
  23. private int seekBackwardTime = 5000; // 5000 milliseconds
  24. private long startTime = 0;
  25. private long finalTime = 0;
  26. private int currentSongIndex = 0;
  27. private boolean isShuffle = false;
  28. private boolean isRepeat = false;
  29. private Handler myHandler = new Handler();
  30.  
  31.  
  32. @Override
  33. public void onCreate(Bundle savedInstanceState) {
  34. super.onCreate(savedInstanceState);
  35. setContentView(R.layout.player);
  36. mContext=this;
  37. mSurrahList=new ArrayList<Model>();
  38. listRawMp3List();
  39.  
  40. listView=(ListView)findViewById(R.id.listView);
  41. mFancyAdapter = new FancyAdapter(mSurrahList);
  42. listView.setAdapter(mFancyAdapter);
  43. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  44. @Override
  45. public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
  46. playSong(i);
  47. }
  48. });
  49. tvomorTitle=(TextView)findViewById(R.id.tvomorTitle);
  50. // All player buttons
  51. btnPlay = (ImageButton) findViewById(R.id.btnPlay);
  52. btnForward = (ImageButton) findViewById(R.id.btnForward);
  53. btnBackward = (ImageButton) findViewById(R.id.btnBackward);
  54. btnNext = (ImageButton) findViewById(R.id.btnNext);
  55. btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
  56. songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
  57. songTitleLabel = (TextView) findViewById(R.id.songTitle);
  58. songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
  59. songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
  60.  
  61. // Mediaplayer
  62. mp = new MediaPlayer();
  63.  
  64. utils = new Utilities();
  65.  
  66. // Listeners
  67. songProgressBar.setOnSeekBarChangeListener(this); // Important
  68. mp.setOnCompletionListener(this); // Important
  69.  
  70. // Getting all songs list
  71.  
  72.  
  73. // By default play first song
  74.  
  75.  
  76. playSong(0);
  77.  
  78. /**
  79. * Play button click event
  80. * plays a song and changes button to pause image
  81. * pauses a song and changes button to play image
  82. * */
  83. btnPlay.setOnClickListener(new View.OnClickListener() {
  84.  
  85. @Override
  86. public void onClick(View arg0) {
  87. // check for already playing
  88. if(mp.isPlaying()){
  89. if(mp!=null){
  90. mp.pause();
  91. // Changing button image to play button
  92. btnPlay.setImageResource(R.drawable.btn_play);
  93. }
  94. }else{
  95. // Resume song
  96. if(mp!=null){
  97. mp.start();
  98. // Changing button image to pause button
  99. btnPlay.setImageResource(R.drawable.btn_pause);
  100. }
  101. }
  102.  
  103. }
  104. });
  105.  
  106. /**
  107. * Forward button click event
  108. * Forwards song specified seconds
  109. * */
  110. btnForward.setOnClickListener(new View.OnClickListener() {
  111.  
  112. @Override
  113. public void onClick(View arg0) {
  114. // get current song position
  115. int currentPosition = mp.getCurrentPosition();
  116. // check if seekForward time is lesser than song duration
  117. if(currentPosition + seekForwardTime <= mp.getDuration()){
  118. // forward song
  119. mp.seekTo(currentPosition + seekForwardTime);
  120. }else{
  121. // forward to end position
  122. mp.seekTo(mp.getDuration());
  123. }
  124. }
  125. });
  126.  
  127. /**
  128. * Backward button click event
  129. * Backward song to specified seconds
  130. * */
  131. btnBackward.setOnClickListener(new View.OnClickListener() {
  132.  
  133. @Override
  134. public void onClick(View arg0) {
  135. // get current song position
  136. int currentPosition = mp.getCurrentPosition();
  137. // check if seekBackward time is greater than 0 sec
  138. if(currentPosition - seekBackwardTime >= 0){
  139. // forward song
  140. mp.seekTo(currentPosition - seekBackwardTime);
  141. }else{
  142. // backward to starting position
  143. mp.seekTo(0);
  144. }
  145.  
  146. }
  147. });
  148.  
  149. /**
  150. * Next button click event
  151. * Plays next song by taking currentSongIndex + 1
  152. * */
  153. btnNext.setOnClickListener(new View.OnClickListener() {
  154.  
  155. @Override
  156. public void onClick(View arg0) {
  157. // check if next song is there or not
  158. if(currentSongIndex < (mSurrahList.size() - 1)){
  159. playSong(currentSongIndex + 1);
  160. currentSongIndex = currentSongIndex + 1;
  161. }else{
  162. // play first song
  163. playSong(0);
  164. currentSongIndex = 0;
  165. }
  166.  
  167. }
  168. });
  169.  
  170. /**
  171. * Back button click event
  172. * Plays previous song by currentSongIndex - 1
  173. * */
  174. btnPrevious.setOnClickListener(new View.OnClickListener() {
  175.  
  176. @Override
  177. public void onClick(View arg0) {
  178. if(currentSongIndex > 0){
  179. playSong(currentSongIndex - 1);
  180. currentSongIndex = currentSongIndex - 1;
  181. }else{
  182. // play last song
  183. playSong(mSurrahList.size() - 1);
  184. currentSongIndex = mSurrahList.size() - 1;
  185. }
  186.  
  187. }
  188. });
  189.  
  190.  
  191.  
  192. }
  193.  
  194. public void listRawMp3List(){
  195. Field[] fields=R.raw.class.getFields();
  196. for(int count=0; count < fields.length; count++){
  197.  
  198. try
  199. {
  200. int id=count;
  201. String name=fields[count].getName();
  202. String path="R.raw."+name;
  203. long resourceID=fields[count].getInt(fields[count]);
  204. mSurrahList.add(new Model(id, name, path, resourceID));
  205. // Toast.makeText(mContext,"resourceID:"+resourceID,Toast.LENGTH_LONG).show();
  206. }
  207. catch (Exception e)
  208. {
  209. Toast.makeText(mContext,"Exception:"+e.toString(),Toast.LENGTH_LONG).show();
  210. }
  211.  
  212. }
  213. }
  214.  
  215. /**
  216. * Function to play a song
  217. * @param songIndex - index of song
  218. * */
  219. public void playSong(int songIndex){
  220. // Play song
  221. try {
  222. mp.reset();
  223. // mp.setDataSource(songsList.get(songIndex).get("songPath"));
  224. Log.e("logg",Uri.parse("android.resource://com.androidhive.musicplayer/" + R.raw.al_ahzab).toString());
  225. Log.e("loggf",Uri.parse("android.resource://com.androidhive.musicplayer/" + mSurrahList.get(songIndex).getResourceID()).toString());
  226. Log.e("logg1",Uri.parse("android.resource://com.androidhive.musicplayer/" + mSurrahList.get(songIndex).getPath()).toString());
  227. // mp.setDataSource(getApplicationContext(),
  228. // Uri.parse("android.resource://com.androidhive.musicplayer/" + "R.raw."+mSurrahList.get(songIndex).getName()));
  229. mp.setDataSource(getApplicationContext(),
  230. Uri.parse("android.resource://com.androidhive.musicplayer/" + mSurrahList.get(songIndex).getResourceID()));
  231. mp.prepare();
  232. mp.start();
  233. // Displaying Song title
  234. String songTitle = mSurrahList.get(songIndex).getName();
  235. songTitleLabel.setText(songTitle);
  236. tvomorTitle.setText("Now playing: "+songTitle);
  237.  
  238. // Changing Button Image to pause image
  239. btnPlay.setImageResource(R.drawable.btn_pause);
  240.  
  241. // set Progress bar values
  242. songProgressBar.setProgress(0);
  243. songProgressBar.setMax(100);
  244.  
  245. // Updating progress bar
  246. updateProgressBar();
  247. } catch (IllegalArgumentException e) {
  248. e.printStackTrace();
  249. } catch (IllegalStateException e) {
  250. e.printStackTrace();
  251. } catch (IOException e) {
  252. e.printStackTrace();
  253. }
  254. }
  255.  
  256. /**
  257. * Update timer on seekbar
  258. * */
  259. public void updateProgressBar() {
  260. mHandler.postDelayed(mUpdateTimeTask, 100);
  261. }
  262.  
  263. /**
  264. * Background Runnable thread
  265. * */
  266. private Runnable mUpdateTimeTask = new Runnable() {
  267. public void run() {
  268. try
  269. {
  270. long totalDuration = mp.getDuration();
  271. long currentDuration = mp.getCurrentPosition();
  272.  
  273. // Displaying Total Duration time
  274. songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
  275. // Displaying time completed playing
  276. songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
  277.  
  278. // Updating progress bar
  279. int progress = utils.getProgressPercentage(currentDuration, totalDuration);
  280. //Log.d("Progress", ""+progress);
  281. songProgressBar.setProgress(progress);
  282.  
  283. // Running this thread after 100 milliseconds
  284. mHandler.postDelayed(this, 100);
  285. }
  286. catch (Exception e)
  287. {
  288.  
  289. }
  290.  
  291. }
  292. };
  293.  
  294. /**
  295. *
  296. * */
  297. @Override
  298. public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
  299.  
  300. }
  301.  
  302. /**
  303. * When user starts moving the progress handler
  304. * */
  305. @Override
  306. public void onStartTrackingTouch(SeekBar seekBar) {
  307. // remove message Handler from updating progress bar
  308. mHandler.removeCallbacks(mUpdateTimeTask);
  309. }
  310.  
  311. /**
  312. * When user stops moving the progress hanlder
  313. * */
  314. @Override
  315. public void onStopTrackingTouch(SeekBar seekBar) {
  316. mHandler.removeCallbacks(mUpdateTimeTask);
  317. int totalDuration = mp.getDuration();
  318. int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
  319.  
  320. // forward or backward to certain seconds
  321. mp.seekTo(currentPosition);
  322.  
  323. // update timer progress again
  324. updateProgressBar();
  325. }
  326.  
  327. /**
  328. * On Song Playing completed
  329. * if repeat is ON play same song again
  330. * if shuffle is ON play random song
  331. * */
  332. @Override
  333. public void onCompletion(MediaPlayer arg0) {
  334.  
  335. // check for repeat is ON or OFF
  336. if(isRepeat){
  337. // repeat is on play same song again
  338. playSong(currentSongIndex);
  339. } else if(isShuffle){
  340. // shuffle is on - play a random song
  341. Random rand = new Random();
  342. currentSongIndex = rand.nextInt((mSurrahList.size() - 1) - 0 + 1) + 0;
  343. playSong(currentSongIndex);
  344. } else{
  345. // no repeat or shuffle ON - play next song
  346. if(currentSongIndex < (mSurrahList.size() - 1)){
  347. playSong(currentSongIndex + 1);
  348. currentSongIndex = currentSongIndex + 1;
  349. }else{
  350. // play first song
  351. playSong(0);
  352. currentSongIndex = 0;
  353. }
  354. }
  355. }
  356.  
  357.  
  358. @Override
  359. public void onDestroy(){
  360. super.onDestroy();
  361. mp.release();
  362. }
  363. private class FancyAdapter extends BaseAdapter {
  364.  
  365. private ArrayList<Model> mData;
  366.  
  367. public FancyAdapter(ArrayList<Model> data) {
  368. mData = data;
  369. }
  370.  
  371. @Override
  372. public int getCount() {
  373. return mData.size();
  374. }
  375.  
  376. @Override
  377. public Model getItem(int position) {
  378. return mData.get(position);
  379. }
  380.  
  381. @Override
  382. public long getItemId(int position) {
  383. return position;
  384. }
  385.  
  386. @Override
  387. public View getView(int position, View convertView, ViewGroup parent) {
  388.  
  389. TextView result;
  390.  
  391. if (convertView == null) {
  392. result = (TextView) getLayoutInflater().inflate(R.layout.text_item, parent, false);
  393. } else {
  394. result = (TextView) convertView;
  395. }
  396.  
  397. final String cheese = getItem(position).name;
  398. result.setText(cheese);
  399.  
  400. return result;
  401. }
  402.  
  403. }
  404. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement