【问题标题】:android music player with service带服务的安卓音乐播放器
【发布时间】:2012-04-04 10:58:22
【问题描述】:

我正在寻找一个用于学习目的的 android 音乐播放器的基本实现。我想要的只是一个带有服务和 oncompletionlistener 的音乐播放器,它会移动到下一个曲目和一个通知。但我还没有找到类似的东西。任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: android android-service android-notifications android-music-player


    【解决方案1】:

    试试这个:

    //class
    public class MusicPlayService extends Service {    
       //media player
    
        private MediaPlayer player;
        //song list
        private ArrayList<Song> songs;
        //current position
        private int songPosn;
        //binder
        private final IBinder musicBind = new MusicBinder(); //very important
        //title of current song
        private String songTitle="";
        private String songAlbumart="";
        private String songDuration="";
        //shuffle flag and random
        private boolean shuffle=false;
        private boolean ispaused=false;
        private Random rand;
        //todo pause music at time of call
        Notification mNotification;
        static RemoteViews mRemoteViews;
        public static int currentPos=0;
        NotificationManager mNotifiManager;
        public static final int NOTIFICATION_IDFOREGROUND_SERVICE=78945;
        public static final String ACTION_STOP="com.yourapp.ACTION_STOP";
        public static final String ACTION_PLAY="com.yourapp.ACTION_PLAY";
        public static final String ACTION_PAUSE="com.yourapp.ACTION_PAUSE";
        public static final String ACTION_RESUME="com.yourapp.ACTION_RESUME";
        public static final String ACTION_NEXT="com.yourapp.ACTION_NEXT";
        public static final String ACTION_PREV="com.yourapp.ACTION_PREV";
        int REQUEST_CODE_STOP=1111;
        int REQUEST_CODE_PAUSE=2222;
        int REQUEST_CODE_RESUME=3333;
        int REQUEST_CODE_NEXT=4444;
        int REQUEST_CODE_PREV=6666;
        int REQUEST_CODE_ACTVITY=5555;
        @Override
        public  void onCreate() {
            super.onCreate();
            //todo//see me
            mNotifiManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            //initialize position
            songPosn=0;
            //random
            rand=new Random();
            //create player
            player = new MediaPlayer();
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            //set listeners
            player.setOnPreparedListener(this);
            player.setOnCompletionListener(this);
            player.setOnErrorListener(this);
    
        }
    
        //pass song list
        public void setList(ArrayList<Song> theSongs){
            songs=theSongs;
        }
        //binder
        public class MusicBinder extends Binder {
            MusicPlayService getService() {
                return MusicPlayService.this;
            }
        }
        //activity will bind to service
        public IBinder onBind(Intent arg0) {
            return musicBind;
        }
        //release resources when unbind
        @Override
        public boolean onUnbind(Intent intent){
            //player.stop();
            //player.release();
            return false;
        }
        //set the song
        public void setSong(int songIndex){
            songPosn=songIndex;
        }
        //play a song
        public void playSong(){
            //play
            player.reset();
            //get song
            Song playSong = songs.get(songPosn);
            //get title
            songTitle=playSong.DISPLAY_NAME;
            songDuration=playSong.DURATION;
            songAlbumart=playSong.ALBUMART;
            //set the data source
            try{
                player.setDataSource(playSong.Path);
            }
            catch(Exception e){
                Log.e("MUSIC SERVICE", "Error setting data source", e);
            }
            player.prepareAsync(); //this will call onPrepared
        }
        @Override
        public void onPrepared(MediaPlayer mp) {
            //start playback
            mp.start();
            //notification
            showControllerInNotification(songTitle, songDuration,songAlbumart);
        }
        //playback methods
        public int getPosn(){
            return player.getCurrentPosition();
        }
    
        public int getDur(){
            return player.getDuration();
        }
    
        public boolean isPng(){
            return player.isPlaying();
        }
    
        public void pausePlayer(){
            player.pause();
        }
        public void stopPlayer(){
            player.stop();
        }
    
        public void seek(int posn){
            player.seekTo(posn);
        }
        public void go(){
            player.start();
        }
    
        //skip to previous track
        public void playPrev(){
            songPosn--;
            if(songPosn<0) songPosn=songs.size()-1;
            playSong();
        }
    
        //skip to next
        public void playNext(){
            if(shuffle){
                int newSong = songPosn;
                while(newSong==songPosn){
                    newSong=rand.nextInt(songs.size());
                }
                songPosn=newSong;
            }
            else{
                songPosn++;
                if(songPosn>=songs.size()) songPosn=0;
            }
            playSong();
        }
        //toggle shuffle
        public void setShuffle(){
            if(shuffle) shuffle=false;
            else shuffle=true;
        }
        public int onStartCommand(Intent intent, int flags, int startId) {
            if (intent != null) {
                String action = intent.getAction();
    
                if (!TextUtils.isEmpty(action)) {
                    if (action.equals(ACTION_PLAY)) {
                            ispaused=false;
                            playSong();
    
                    }else if(action.equals(ACTION_PAUSE)) {
                        pausePlayer();
                        currentPos = getPosn();
                        ispaused=true;
    
    
                    }else if(action.equals(ACTION_RESUME)) {
                        seek(currentPos);
    
                        ispaused=false;
                        go();
    
                    }
                    else if(action.equals(ACTION_STOP)) {
                        ispaused=false;
                        player.stop();
                        mNotifiManager.cancel(NOTIFICATION_IDFOREGROUND_SERVICE);
                    }
                    else if(action.equals(ACTION_NEXT)) {
                        ispaused=false;
                        playNext();
                    }
                    else if(action.equals(ACTION_PREV)) {
                        ispaused=false;
                        playPrev();
                    }
                }
            }
    
            return super.onStartCommand(intent, flags, startId);
    
        }
        @Override
        public void onDestroy() {
            //player.stop();
            stopForeground(true);
        }
        @Override
        public void onLowMemory() {
    
        }
        private void showControllerInNotification(String title,String duration,String songAlbumart) {
            PendingIntent pendingIntent = null;
            Intent intent = null;
    
            //Inflate a remote view with a layout which you want to display in the notification bar.
            if (mRemoteViews == null) {
                mRemoteViews = new RemoteViews(getPackageName(),
                        R.layout.status_bar);
            }
            if(songAlbumart=="")
            mRemoteViews.setImageViewResource(R.id.status_bar_album_art,R.drawable.musicplayericon);
            else {
                //Drawable image = Drawable.createFromPath(songAlbumart);
                Bitmap bitmap = BitmapFactory.decodeFile(songAlbumart);
                mRemoteViews.setImageViewBitmap(R.id.status_bar_album_art, bitmap);
                //mRemoteViews.setImageViewResource(R.id.status_bar_album_art, image);
            }
            mRemoteViews.setTextViewText(R.id.status_bar_track_name, title);
    
            float dua= Float.valueOf(duration);
            dua=dua/60000;
            //mRemoteViews.setTextViewText(R.id.status_bar_progress_music, String.format("%.2f", dua));
            mRemoteViews.setImageViewResource(R.id.status_bar_playpause, R.drawable.apollo_holo_dark_pause);
            mRemoteViews.setImageViewResource(R.id.status_bar_next, R.drawable.apollo_holo_dark_next);
            //Define what you want to do after clicked the button in notification.
            //Here we launcher a service by an action named "ACTION_STOP" which will stop the music play.
            intent = new Intent(ACTION_STOP);
            pendingIntent = PendingIntent.getService(getApplicationContext(),
                    REQUEST_CODE_STOP, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mRemoteViews.setOnClickPendingIntent(R.id.status_bar_collapse,
                    pendingIntent);
    
            //mRemoteViews.setBackgroundColor(0x0000FF00);
            Intent intentpause = new Intent(ACTION_PAUSE);
            PendingIntent pendingIntentpause = PendingIntent.getService(getApplicationContext(),
                    REQUEST_CODE_PAUSE, intentpause,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mRemoteViews.setOnClickPendingIntent(R.id.status_bar_playpause,
                    pendingIntentpause);
    
            Intent intentnext = new Intent(ACTION_NEXT);
            PendingIntent pendingIntentnext = PendingIntent.getService(getApplicationContext(),
                    REQUEST_CODE_NEXT, intentnext,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mRemoteViews.setOnClickPendingIntent(R.id.status_bar_next,
                    pendingIntentnext);
    
            Intent intentprev = new Intent(ACTION_PREV);
            PendingIntent pendingIntentprev = PendingIntent.getService(getApplicationContext(),
                    REQUEST_CODE_PREV, intentprev,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mRemoteViews.setOnClickPendingIntent(R.id.status_bar_prev,
                    pendingIntentprev);
    
    
            Intent intentactivity=new Intent(getApplicationContext(),ListMusic.class);
            PendingIntent pendingIntentActivity = PendingIntent.getActivity(getApplicationContext(),
                    REQUEST_CODE_ACTVITY, intentactivity,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            //Create the notification instance.
            mNotification = new NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.drawable.notificationimage)
                    .setOngoing(true)
                    .setWhen(System.currentTimeMillis())
                    .setContentIntent(pendingIntentActivity)
                    .setContent(mRemoteViews)
                    .build();
            //mNotification.bigContentView=mRemoteViews;
            //Show the notification in the notification bar.
    
            mNotifiManager.notify(NOTIFICATION_IDFOREGROUND_SERVICE, mNotification);
        }
    
    
        @Override
        public void onCompletion(MediaPlayer mp) {
            //check if playback has reached the end of a track
            if(player.getCurrentPosition()>0){
                mp.reset();
                playNext();
                Log.e("MUSIC PLAYER", "Staring Next Song:"+songTitle);
            }
        }
    
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.e("MUSIC PLAYER", "Playback Error");
            mp.reset();
            return false;
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      试试这个代码

      VideoView videoView = (VideoView)findViewById(R.id.myvideoview);
      
                   videoView.setOnCompletionListener(this);//checks when end
      
                   File path = new File(mPath + "/" + "your file name");
      
                   videoView.setVideoPath(path.getAbsolutePath());
                   MediaController mediaController = new MediaController(this);
                   mediaController.setMediaPlayer(videoView);
                   mediaController.setAnchorView(videoView);
      
                   videoView.setMediaController(mediaController);
                   videoView.requestFocus();
                   videoView.start();
      

      更多请看这个 http://www.vogella.de/articles/AndroidMedia/article.html

      【讨论】:

      • 如果您发现其中有任何问题,请告诉我
      • 我实际上是在寻找一些东西,其中包括与服务的绑定并在服务被调用时显示通知。
      • 按服务你想说你想让音乐播放器从服务开始还是什么??
      • 我的意思是,当我通过活动运行音频文件时,即使活动关闭,它也应该继续运行。我想这必须使用服务来实现。这就是我想要的。
      • 好的,那么你必须在你的活动中启动一个服务,你必须在服务中实现音乐播放器
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      相关资源
      最近更新 更多