小杨啵啵 2016-01-26 13:42 采纳率: 0%
浏览 2530

为什么 seekbar进度不能与音乐的播放同步起来?

package edu.feicui.e.play;

import java.io.IOException;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import edu.feicui.e.R;

public class PlayActivitty extends Activity implements

OnClickListener, OnSeekBarChangeListener, OnCompletionListener {
MediaPlayer mediaPlayer;
SeekBar seekbar;
int position;
int time;
int max;
private TextView btn1;
private TextView btn2;
int[] raws = {R.raw.grow, R.raw.sanxia, R.raw.missingyou};
int index;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);
    btn1 = (Button) findViewById(R.id.btn1);
    btn1.setOnClickListener(this);
    btn2 = (Button) findViewById(R.id.btn2);
    btn2.setOnClickListener(this);
    seekbar = (SeekBar) findViewById(R.id.skb);
    seekbar.setMax(mediaPlayer.getDuration());
    seekbar.setOnSeekBarChangeListener(this);
    // 有问题
    // PlayActivitty pactivity = new PlayActivitty();

}

@Override
public void onContentChanged() {
    super.onContentChanged();
    initCom();
    Player();

}
public void initCom() {
    mediaPlayer = new MediaPlayer();
    index = 0;
    position = mediaPlayer.getCurrentPosition();

    time = mediaPlayer.getDuration();
    max = seekbar.getMax();
    new playThread().start();
}

/**
 * 播放音乐
 */
public void Player() {
    // 1.idle

    // mediaPlayer=mediaPlayer.create(this, R.raw.grow);代替1-3步骤
    // 2.init初始化
    AssetFileDescriptor afd = getResources().openRawResourceFd(raws[index]);
    try {
        mediaPlayer.setDataSource(afd.getFileDescriptor(),
                afd.getStartOffset(), afd.getLength());
        // 3准备
        mediaPlayer.prepare();
        // 4启动
        mediaPlayer.start();
        // new Thread(this).start();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // 设置音乐播放完的监听

    mediaPlayer.setOnCompletionListener(this);

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn1 :
            // 播放/暂停
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                btn1.setText("暂停");
            } else {
                mediaPlayer.start();
                btn1.setText("播放");
            }
            break;
        case R.id.btn2 :
            // 单曲播放/顺序播放
            // true 单曲 false 顺序
            // 获取当前的
            mediaPlayer.setLooping(!mediaPlayer.isLooping());
            if (mediaPlayer.isLooping()) {
                btn2.setText("单曲");
            } else {
                btn2.setText("顺序");
            }

            break;
    }
}
@Override
protected void onDestroy() {
    // 处理 :没有随着APP结束而结束
    if (null != mediaPlayer) {
        mediaPlayer.release();
    }
    super.onDestroy();
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
        boolean fromUser) {
    mediaPlayer.seekTo(progress);// 这里就是音乐播放器播放的位子
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    mediaPlayer.seekTo(seekbar.getProgress());// 歌曲找位置

}
@Override
public void onCompletion(MediaPlayer mp) {
    // 播放下一首
    try {
        playNext();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public void playNext() throws IllegalArgumentException,
        IllegalStateException, IOException {
    index++;
    mediaPlayer.reset();
    AssetFileDescriptor afd = getResources().openRawResourceFd(
            raws[index % raws.length]);
    mediaPlayer.setDataSource(afd.getFileDescriptor(),
            afd.getStartOffset(), afd.getLength());
    mediaPlayer.prepareAsync();
    mediaPlayer.start();
}
// seekbar进度条随音乐播放而更新(可能就是问题项)
class playThread extends Thread {
    @Override
    public void run() {
        while (true) {
            seekbar.setProgress(position * max / time);
            try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

}

  • 写回答

2条回答

  • 91program 博客专家认证 2016-01-26 14:26
    关注

    最好是将音乐播放,写成服务。否则,不在 Activity 时会有问题。提供你一个音乐服务实现的实例代码:

     package com.hs.leozheng.phonelinkhs;
    
    import java.util.List;
    
    import android.annotation.SuppressLint;
    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.media.MediaPlayer;
    import android.media.MediaPlayer.OnCompletionListener;
    import android.media.MediaPlayer.OnPreparedListener;
    import android.os.Handler;
    import android.os.IBinder;
    import android.os.Message;
    import android.util.Log;
    
    import com.hs.leozheng.phonelinkhs.MusicListActivity;
    import com.hs.leozheng.phonelinkhs.AudioMediaInfo;
    import com.hs.leozheng.phonelinkhs.AppConstant;
    
    /***
     * leo
     * 音乐播放服务
     */
    @SuppressLint("NewApi")
    public class PlayerService extends Service {
        private MediaPlayer mediaPlayer;    // 媒体播放器对象
        private String path;                // 音乐文件路径
        private int msg;
        private boolean isPause;            // 暂停状态
        private int current = 0;            // 记录当前正在播放的音乐
        private List<AudioMediaInfo> mp3Infos;      // 存放 AudioMediaInfo 对象的集合
        private int status = 3;             // 播放状态,默认为顺序播放
        private MyReceiver myReceiver;      // 自定义广播接收器
        private int currentTime;            // 当前播放进度
        private int duration;               // 播放长度
    
        /**
         * handler 用来接收消息,来发送广播更新播放时间
         */
        @SuppressLint("HandlerLeak")
        private Handler handler = new Handler() {
    
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    if(mediaPlayer != null) {
                        currentTime = mediaPlayer.getCurrentPosition(); // 获取当前音乐播放的位置
                        duration = mediaPlayer.getDuration();
    
                        Intent intent = new Intent();
                        intent.setAction(AppConstant.AUDIO_SEND_CURRENT);
                        intent.putExtra("currentTime", currentTime);
                        intent.putExtra("totalTime", duration);
                        sendBroadcast(intent); // 给 PlayerActivity 发送广播
                        handler.sendEmptyMessageDelayed(1, 100);
                    }
                }
            };
        };
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.i("service", "service created");
            mediaPlayer = new MediaPlayer();
            mp3Infos = MusicListActivity.getMp3Infos(PlayerService.this);
    
            myReceiver = new MyReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(AppConstant.AUDIO_CTRL_ACTION);
            registerReceiver(myReceiver, filter);
    
            /**
             * 设置音乐播放完成时的监听器
             */
            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
    
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (1 == status) {          // 单曲循环
                        mediaPlayer.start();
                    } else if (2 == status) {   // 全部循环
                        current++;
                        if(current > mp3Infos.size() - 1) { // 变为第一首的位置继续播放
                            current = 0;
                        }
                        path = mp3Infos.get(current).GetUrl();
    
                        Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
                        sendIntent.putExtra("current", current);
                        sendIntent.putExtra("url", path);
                        sendIntent.putExtra("total", mp3Infos.size());
                        // 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到
                        sendBroadcast(sendIntent);
                        play(0);
                    } else if (3 == status) {   // 顺序播放
                        current++;              // 下一首位置
                        if (current <= mp3Infos.size() - 1) {
                            path = mp3Infos.get(current).GetUrl();
                            Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
                            sendIntent.putExtra("current", current);
                            sendIntent.putExtra("url", path);
                            sendIntent.putExtra("total", mp3Infos.size());
    
                            sendBroadcast(sendIntent);
                            play(0);
                        }else {
                            mediaPlayer.seekTo(0);
                            current = 0;
                            path = mp3Infos.get(current).GetUrl();
                            Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
                            sendIntent.putExtra("current", current);
                            sendIntent.putExtra("url", path);
                            sendIntent.putExtra("total", mp3Infos.size());
    
                            sendBroadcast(sendIntent);
                        }
                    } else if (4 == status) {   // 随机播放
                        current = getRandomIndex(mp3Infos.size() - 1);
                        path = mp3Infos.get(current).GetUrl();
                        Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
                        sendIntent.putExtra("current", current);
                        sendIntent.putExtra("url", path);
                        sendIntent.putExtra("total", mp3Infos.size());
    
                        sendBroadcast(sendIntent);
                        play(0);
                    }
                }
            });
        }
    
        /**
         * 获取随机位置
         */
        protected int getRandomIndex(int end) {
            int index = (int) (Math.random() * end);
            return index;
        }
    
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    
        @SuppressWarnings("deprecation")
        @Override
        public void onStart(Intent intent, int startId) {
            path = intent.getStringExtra("url");                // 歌曲路径
            current = intent.getIntExtra("listPosition", -1);   // 当前播放歌曲的在 mp3Infos 的位置
            Log.i("Play Service", "onStart current is: " + Integer.toString(current));
            msg = intent.getIntExtra("MSG", 0);                 // 播放信息
            AppConstant.PlayerMsg msgEnum = AppConstant.PlayerMsg.values()[msg];
            if (AppConstant.PlayerMsg.PLAY_MSG == msgEnum) {    // 直接播放音乐
                Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
                sendIntent.putExtra("current", current);
                sendIntent.putExtra("url", path);
                sendIntent.putExtra("total", mp3Infos.size());
                // 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到
                sendBroadcast(sendIntent);
    
                play(0);
            }
            else if (AppConstant.PlayerMsg.PAUSE_MSG == msgEnum) {          // 暂停
                pause();
            }
            else if (AppConstant.PlayerMsg.STOP_MSG == msgEnum) {           // 停止
                stop();
            }
            else if (AppConstant.PlayerMsg.CONTINUE_MSG == msgEnum) {       // 继续播放
                resume();
            }
            else if (AppConstant.PlayerMsg.PRIVIOUS_MSG == msgEnum) {       // 上一首
                previous();
            }
            else if (AppConstant.PlayerMsg.NEXT_MSG == msgEnum) {           // 下一首
                next();
            }
            else if (AppConstant.PlayerMsg.PROGRESS_CHANGE == msgEnum) {    // 进度更新
                currentTime = intent.getIntExtra("progress", -1);
                play(currentTime);
            }
            else if (AppConstant.PlayerMsg.PLAYING_MSG == msgEnum) {
                handler.sendEmptyMessage(1);
            }
    
            super.onStart(intent, startId);
        }
    
        /**
         * 播放音乐
         *
         * @param position
         */
        private void play(int currentTime) {
            try {
                mediaPlayer.reset();                // 把各项参数恢复到初始状态
                mediaPlayer.setDataSource(path);
    
                Intent commonCtrl_intent = new Intent();
                commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);
                commonCtrl_intent.putExtra("ACTION", "UIPlayingFilename");
                // 对 URL 进行处理: 保显示文件名,不显示目录
                int find = path.lastIndexOf('/') + 1;
                String strFilename = null;
                if(-1 != find)
                {
                    strFilename = path.substring(find);
                    commonCtrl_intent.putExtra("filename", strFilename);
                    sendBroadcast(commonCtrl_intent);
                }
    
                mediaPlayer.prepare();              // 进行缓冲
                mediaPlayer.setOnPreparedListener(new PreparedListener(currentTime));   // 注册一个监听器
                handler.sendEmptyMessage(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 暂停音乐
         */
        private void pause() {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                isPause = true;
    
                Intent commonCtrl_intent = new Intent();
                commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);
                commonCtrl_intent.putExtra("ACTION", "UIPlayingStatus");
                commonCtrl_intent.putExtra("playingStatus", 2);
                sendBroadcast(commonCtrl_intent);
            }
        }
    
        private void resume() {
            if (isPause) {
                mediaPlayer.start();
                isPause = false;
    
                Intent commonCtrl_intent = new Intent();
                commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);
                commonCtrl_intent.putExtra("ACTION", "UIPlayingStatus");
                commonCtrl_intent.putExtra("playingStatus", 1);
                sendBroadcast(commonCtrl_intent);
            }
        }
    
        /**
         * 上一首
         */
        private void previous() {
            int size = mp3Infos.size();
            if((current - 1) >= 0) {
                current--;
            }
            else {
                current = size - 1;
            }
            path = mp3Infos.get(current).GetUrl();
    
            Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
            sendIntent.putExtra("current", current);
            sendIntent.putExtra("url", path);
            sendIntent.putExtra("total", size);
            // 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到
            sendBroadcast(sendIntent);
            play(0);
        }
    
        /**
         * 下一首
         */
        private void next() {
            int size = mp3Infos.size();
            if((current + 1) <= (size - 1)) {
                current++;
            }
            else {
                current = 0;
            }
            path = mp3Infos.get(current).GetUrl();
    
            Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
            sendIntent.putExtra("current", current);
            sendIntent.putExtra("url", path);
            sendIntent.putExtra("total", size);
            // 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到
            sendBroadcast(sendIntent);
            play(0);
        }
    
        /**
         * 停止音乐
         */
        private void stop() {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                try {
                    mediaPlayer.prepare(); // 在调用 stop 后如果需要再次通过 start 进行播放,需要之前调用 prepare 函数
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
                Intent commonCtrl_intent = new Intent();
                commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);
                commonCtrl_intent.putExtra("ACTION", "UIPlayingStatus");
                commonCtrl_intent.putExtra("playingStatus", 3);
                sendBroadcast(commonCtrl_intent);
            }
        }
    
        @Override
        public void onDestroy() {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }
    
        /**
         *
         * 实现一个 OnPrepareLister 接口,当音乐准备好的时候开始播放
         *
         */
        private final class PreparedListener implements OnPreparedListener {
            private int currentTime;
    
            public PreparedListener(int currentTime) {
                this.currentTime = currentTime;
            }
    
            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaPlayer.start();    // 开始播放
                if (currentTime > 0) {  // 如果音乐不是从头播放
                    mediaPlayer.seekTo(currentTime);
                }
                Intent intent = new Intent();
                intent.setAction(AppConstant.AUDIO_SEND_DURATION);
                duration = mediaPlayer.getDuration();
                intent.putExtra("duration", duration);  // 通过 Intent 来传递歌曲的总长度
                sendBroadcast(intent);
            }
        }
    
        public class MyReceiver extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                AppConstant.PlayerMsg msgEnum = AppConstant.PlayerMsg.APP_CONSTANT_MAX;
                String action = intent.getAction();
                int msg = intent.getIntExtra("MSG", -1);
                int mode = intent.getIntExtra("mode", 3);
                if(msg > 0) {
                    msgEnum = AppConstant.PlayerMsg.values()[msg];
                }
                if(action.equals(AppConstant.AUDIO_CTRL_ACTION)) {
                    Log.v("Play Service", "Control: " + Integer.toString(msg));
                    if(msgEnum == AppConstant.PlayerMsg.PRIVIOUS_MSG)
                    {
                        Log.v("Play Service", "Control.Prev");
                        previous();
                    }
                    else if(msgEnum == AppConstant.PlayerMsg.NEXT_MSG)
                    {
                        Log.v("Play Service", "Control.Next");
                        next();
                    }
                    else if(msgEnum == AppConstant.PlayerMsg.PLAY_MODE)
                    {
                        Log.v("Play Service", "Control.Mode: " + Integer.toString(mode));
                    }
                    else if(msgEnum == AppConstant.PlayerMsg.CONTINUE_MSG)
                    {
                        Log.v("Play Service", "Control.Continue");
                        resume();
                    }
                    else if(msgEnum == AppConstant.PlayerMsg.PAUSE_MSG)
                    {
                        Log.v("Play Service", "Control.Pause");
                        pause();
                    }
                }
            }
        }
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型