seekbar不在musicplayer工作

时间:2017-08-02 19:58:30

标签: java android xml user-interface seekbar

我正在尝试创建一个音乐播放器应用程序,其他所有工作正常,除了搜索栏。我已经在SO上阅读了其他类似的问题,但它根本没有帮助。当歌曲开始播放时,搜索栏不会开始移动。在触摸搜索栏时,会显示歌曲的总持续时间,但不会显示当前持续时间或已用时间。您也可以使用搜索栏向前和向后移动歌曲,但拇指位置不会改变,应用程序也会停止响应。任何人都可以帮我吗?

PlaylistActivity.Java

package com.example.dell_1.myapp3;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class PlayListActivity extends Activity {

    private String[] mAudioPath;
    private MediaPlayer mMediaPlayer;
    private String[] mMusicList;
    private SeekBar songProgressBar;
    private Handler mHandler = new Handler();
    ;
    private Utilities utils;
    private TextView songCurrentDurationLabel;
    private TextView songTotalDurationLabel;
    int currentPosition = 0;

    MediaMetadataRetriever metaRetriver;
    byte[] art;
    ImageView album_art;
    TextView album;
    TextView artist;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_list);
        mMediaPlayer = new MediaPlayer();
        utils = new Utilities();

        ListView mListView = (ListView) findViewById(R.id.list);
        mMusicList = getAudioList();

        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, mMusicList);
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                                    long arg3) {

                try {
                    playSong(mAudioPath[arg2]);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private String[] getAudioList() {
        final Cursor mCursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
                "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");

        int count = mCursor.getCount();


        String[] songs = new String[count];
        mAudioPath = new String[count];
        int i = 0;
        if (mCursor.moveToFirst()) {
            do {
                songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                i++;
            } while (mCursor.moveToNext());
        }

        mCursor.close();

        return songs;
    }


    private void playSong(String path) throws IllegalArgumentException,
            IllegalStateException, IOException {

        setContentView(R.layout.activity_android_building_music_player);
        Log.d("ringtone", "playSong :: " + path);

        mMediaPlayer.reset();
        mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                currentPosition = currentPosition + 1;
                try {
                    playSong(mAudioPath[currentPosition]);
                } catch (Exception er) {
                    er.printStackTrace();
                }
            }
        });
        acv(path);
        abc();
        cde();
        fgh();
        ijk();
        lmn();
        jjj();
    }

    public void acv(String path) {
        getInit();

        metaRetriver = new MediaMetadataRetriever();
        metaRetriver.setDataSource(path);
        try {
            art = metaRetriver.getEmbeddedPicture();
            Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
            album_art.setImageBitmap(songImage);
            album.setText(metaRetriver
                    .extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
            artist.setText(metaRetriver
                    .extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
        } catch (Exception e) {
            album_art.setBackgroundColor(Color.GRAY);
            album.setText("Unknown Album");
            artist.setText("Unknown Artist");
        }

    }

    public void getInit() {
        album_art = (ImageView) findViewById(R.id.coverart1);
        album = (TextView) findViewById(R.id.Album);
        artist = (TextView) findViewById(R.id.artist_name);
    }


    public void abc() {
        ImageButton btnPlay1 = (ImageButton) findViewById(R.id.btnPlay1);
        btnPlay1.setBackgroundColor(Color.TRANSPARENT);
        btnPlay1.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View v) {
                        if (mMediaPlayer.isPlaying()) {
                            mMediaPlayer.pause();
                        } else {
                            mMediaPlayer.start();
                        }

                    }
                });
    }


    public void cde() {
        ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);
        btnNext.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View view) {
                        currentPosition = currentPosition + 1;
                        try {
                            playSong(mAudioPath[currentPosition]);
                        } catch (Exception er) {
                            er.printStackTrace();
                        }

                    }
                }
        );
    }

    public void fgh() {
        ImageButton btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
        btnPrevious.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View view) {
                        currentPosition = currentPosition - 1;
                        try {
                            playSong(mAudioPath[currentPosition]);
                        } catch (Exception er) {
                            er.printStackTrace();
                        }

                    }
                }
        );
    }

    public void ijk() {
        ImageButton btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
        btnRepeat.setOnClickListener
                (new View.OnClickListener() {
                    public void onClick(View arg0) {
                        mMediaPlayer.setLooping(true);
                    }
                });
    }

    public void lmn() {
        ImageButton btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
        btnShuffle.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View view) {
                        List<String> arr = Arrays.asList(mAudioPath);
                        Collections.shuffle(arr);
                        arr.toArray(mAudioPath);
                    }
                }
        );
    }

    public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    /**
     * Background Runnable thread
     */
    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            int totalDuration = mMediaPlayer.getDuration();
            long currentDuration = mMediaPlayer.getCurrentPosition();

            songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
            songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);


            // 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);
            songProgressBar.setMax(totalDuration);

            // Running this thread after 100 milliseconds
            mHandler.postDelayed(this, 100);
        }
    };

            public void jjj(){
                songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);

            songProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    updateProgressBar();

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    mHandler.removeCallbacks(mUpdateTimeTask);
                    updateProgressBar();

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    mHandler.removeCallbacks(mUpdateTimeTask);
                    int totalDuration = mMediaPlayer.getDuration();
                    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

                    // forward or backward to certain seconds
                    mMediaPlayer.seekTo(currentPosition);

                    // update timer progress again
                    updateProgressBar();

                }
            });

            }
        }

Utilities.java

package com.example.dell_1.myapp3;

public class Utilities {


    public String milliSecondsToTimer(long milliseconds){
        String finalTimerString = "";
        String secondsString = "";

        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);
        if(hours > 0){
            finalTimerString = hours + ":";
        }

        if(seconds < 10){
            secondsString = "0" + seconds;
        }else{
            secondsString = "" + seconds;}

        finalTimerString = finalTimerString + minutes + ":" + secondsString;

        return finalTimerString;
    }


    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();
    }


    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;
    }
}

XML文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:id="@+id/player_header_bg"
        android:layout_width="fill_parent"
        android:layout_height="60dip"
        android:layout_alignParentTop="true"
        android:background="@layout/bg_player_header"
        android:paddingLeft="5dp"
        android:paddingRight="5dp">

        <ImageButton
            android:id="@+id/btnPlaylist"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:paddingLeft="300dp"
            android:background="@null"
            android:src="@drawable/btn_playlist" />
    </LinearLayout>

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/player_header_bg"
    android:paddingLeft="250dp">



    <ImageView
            android:id="@+id/coverart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="fitXY"
            android:paddingLeft="250dp"
            android:layout_centerHorizontal="true"
            />


</RelativeLayout>

    <LinearLayout
        android:id="@+id/player_footer_bg"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="@layout/bg_player_footer"
        android:gravity="center">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:weightSum="1"
           >

            <RelativeLayout
                android:layout_width="300dp"
                android:layout_height="match_parent">


                <ImageButton
                    android:id="@+id/btnPrevious"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_weight="2.40"
                    android:background="@null"
                    android:paddingLeft="10dp"
                    android:src="@drawable/btn_previous" />

                <ImageButton
                    android:id="@+id/btnPlay1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:clickable="true"
                    android:focusable="true"
                    android:src="@drawable/btn_play" />


                <ImageButton
                    android:id="@+id/btnNext"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:src="@drawable/btn_next" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>

    <SeekBar
        android:id="@+id/songProgressBar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/player_footer_bg"
        android:layout_alignLeft="@+id/timerDisplay"
        android:layout_alignStart="@+id/timerDisplay"
        android:splitTrack="false"
        android:maxHeight="3dp"
        android:layout_marginBottom="10dp"
        android:paddingLeft="6dp"
        android:paddingRight="6dp"
        android:progressDrawable="@drawable/seekbar_progress"
        android:thumb="@drawable/download8" />




    <LinearLayout
        android:id="@+id/timerDisplay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/songProgressBar"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp">


        <TextView
            android:id="@+id/songCurrentDurationLabel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:textColor="#eeeeee"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/songTotalDurationLabel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:textColor="#04cbde"
            android:textStyle="bold" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_above="@+id/timerDisplay"
        android:layout_alignLeft="@+id/timerDisplay"
        android:layout_alignStart="@+id/timerDisplay">


        <ImageView
            android:id="@+id/coverart1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:layout_marginBottom="200dp"
            android:scaleType="fitXY"
            android:background="@drawable/download"
            android:layout_centerInParent="true"
            android:paddingRight="60dp"
            />

        <ImageButton
            android:id="@+id/btnRepeat"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/btn_repeat"
            android:layout_marginTop="140dp"
            android:paddingRight="6dp"
            android:layout_alignRight="@id/coverart1"
            android:layout_alignTop = "@id/coverart1"
            android:layout_alignParentTop="true"
            />

        <ImageButton
            android:id="@+id/btnShuffle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="200dp"
            android:background="@null"
            android:src="@drawable/btn_shuffle"
            android:paddingRight="6dp"
            android:layout_alignRight="@id/coverart1"
            android:layout_alignTop = "@id/coverart1"
            android:layout_alignParentTop="true"/>


        <TextView
            android:id="@+id/artist_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="330dp"
            android:layout_centerHorizontal="true"
            android:text="null"
            android:textSize="18dp"
            android:gravity="center"/>

        <TextView
            android:id="@+id/Album"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="380dp"
            android:layout_centerHorizontal="true"
            android:text="null"
            android:textSize="18dp"
            android:gravity="center"/>


    </RelativeLayout>
</RelativeLayout>

0 个答案:

没有答案