exoplayer前台服务mp3片段

pcww981p  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(217)

您好,我正在制作一个如下图所示的播放器:
照片
我想让它在前景中播放音乐片段。你能告诉我我做错了什么吗?
我有一些适配器中的歌曲列表,在那里我打开了“playerfragment”

holder.currentBox.setOnClickListener(v -> {
        PlayerFragment playerFragment = new PlayerFragment(playlist, position);
         activity.getSupportFragmentManager().beginTransaction().addToBackStack("null").replace(R.id.main_fragment_container, playerFragment).commit();
    });

我将从firebase获取的播放列表和列表中的currentindex传递给这个片段。
这里是玩家及其服务的代码

public class PlayerFragment extends Fragment {
        private FirebaseStorage storage;
        private ImageButton fav_btn;
        private Button settings_btn;
        private final Playlist playlist;
        int position;
        private ImageView song_img;

        private TextView title, author;

        private PlayerView playerView;

        private BackgroundService mService;
        private boolean mBound = false;
        private String mUrl, mTitle, mSummary, mImage;
        private Intent intent;
        private String shareableLink;

        public PlayerFragment(Playlist playlist, int position){
            this.playlist = playlist;
            this.position=position;
            //We are sending playlist to this player and let it play all of it
        }

        private ServiceConnection mConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                BackgroundService.LocalBinder binder = (BackgroundService.LocalBinder) iBinder;
                mService = binder.getService();
                mBound = true;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBound = false;
            }
        };

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState)
        {
            // Inflate the layout for this fragment
          View view=  inflater.inflate(R.layout.fragment_player, container, false);
          storage = FirebaseStorage.getInstance();
          title = view.findViewById(R.id.player_song_title);
          author = view.findViewById(R.id.player_song_author);
          song_img =view.findViewById(R.id.player_song_img);
            playerView= view.findViewById(R.id.player_view);

            mImage = playlist.getSongs().get(0).getImage_url();
            mUrl = playlist.getSongs().get(0).getPath();
            mTitle = playlist.getSongs().get(0).getTitle();
            mSummary = playlist.getSongs().get(0).getAuthor();
            intent = new Intent(requireActivity(), BackgroundService.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("playlist", playlist);
            intent.putExtra("bundle", bundle);
            Util.startForegroundService(requireActivity(), intent);
            playerView.setUseController(true);
            playerView.showController();
            playerView.setControllerAutoShow(true);
            playerView.setControllerHideOnTouch(false);

          return view;
        }

        @Override
        public void onStart() {
            super.onStart();
            getActivity().bindService(intent,mConnection, Context.BIND_AUTO_CREATE);
            initializePlayer();
            setupUI();
        }

        @Override
        public void onStop() {
            super.onStop();
            getActivity().unbindService(mConnection);
            mBound = false;
        }

        private void setupUI(){
            title.setText(playlist.getSongs().get(position).getTitle());
            author.setText(playlist.getSongs().get(position).getAuthor());
            Glide.with(getContext()).load(playlist.getSongs().get(position).getImage_url()).into(song_img);

        }

        private void initializePlayer(){
            SimpleExoPlayer player = mService.getPlayerInstance();
            playerView.setPlayer(player);
        }

        class ExoListener implements Player.Listener{
            Player player = playerView.getPlayer();

            @Override
            public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                // Video playback status
                title.setText(playlist.getSongs().get(player.getCurrentWindowIndex()).getTitle());
                author.setText(playlist.getSongs().get(player.getCurrentWindowIndex()).getAuthor());
                Glide.with(getContext()).load(playlist.getSongs().get(player.getCurrentWindowIndex()).getImage_url()).into(song_img);
                System.out.println("Gramy piosenke: "+playlist.getSongs().get((int) player.getCurrentWindowIndex()).getTitle());

                Log.d("playbackState = " + playbackState + " playWhenReady = " + playWhenReady,"Exo");
                switch (playbackState){
                    case Player.STATE_IDLE:
                        // free
                        break;
                    case Player.STATE_BUFFERING:
                        // Buffer
                        break;
                    case Player.STATE_READY:
                        // Get ready
                        break;
                    case Player.STATE_ENDED:
                        // End
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPlayerError(ExoPlaybackException error) {
                // Report errors
                switch (error.type){
                    case ExoPlaybackException.TYPE_SOURCE:
                        // Error loading resources
                        break;
                    case ExoPlaybackException.TYPE_RENDERER:
                        // Errors in rendering
                        break;
                    case ExoPlaybackException.TYPE_UNEXPECTED:
                        // unexpected error
                        break;
                }
            }

        }

    }

以下服务:

public class BackgroundService extends Service implements ExoPlayer.EventListener {
        private final IBinder mBinder = new LocalBinder();
        private DataSource.Factory dataSourceFactory;
        private MediaSource mediaSource;
        private SimpleExoPlayer player;
        private Playlist playlist;
        private Context context;
        private ArrayList<Song> songs;
        private final String streamUrl = "https://firebasestorage.googleapis.com/v0/b/altas-notas.appspot.com/o/songs%2Fbad%20bunny%2Fyhlqmdlg%2FHABLAMOS%20MA%C3%91ANA.mp3?alt=media&token=07a9d499-22b5-4586-9b57-7219b2812335";
        private TrackSelector trackSelector;

        private String CHANNEL_ID="6", NOTIFICATION_ID="8";

        @Override
        public void onCreate() {
            super.onCreate();
            context =this;
        }

        @Override
        public IBinder onBind(Intent intent) {
           Bundle bundle  = (Bundle) intent.getExtras().get("bundle");
           playlist = bundle.getParcelable("playlist");
            System.out.println(songs.size());
            return mBinder;

        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            if (player == null) {
                startPlayer();
                PlayerNotificationManager playerNotificationManager = new PlayerNotificationManager(
                        context, CHANNEL_ID, Integer.parseInt(NOTIFICATION_ID), new PlayerNotificationManager.MediaDescriptionAdapter() {
                    @Override
                    public CharSequence getCurrentContentTitle(Player player) {
                        return player.getCurrentMediaItem().mediaMetadata.title;
                    }

                    @Nullable
                    @Override
                    public PendingIntent createCurrentContentIntent(Player player) {
                        Intent intent = new Intent(context, MainActivity.class);
                        return PendingIntent.getActivity(context, 0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                    }

                    @Nullable
                    @Override
                    public CharSequence getCurrentContentText(Player player) {
                        return player.getCurrentMediaItem().mediaMetadata.artist;
                    }

                    @Nullable
                    @Override
                    public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
                        return null;
                    }
                },
                new PlayerNotificationManager.NotificationListener() {
                            @Override
                            public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
                               startForeground();
                            }

                            @Override
                            public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
                                if (dismissedByUser) {
                                    // Do what the app wants to do when dismissed by the user,
                                    // like calling stopForeground(true); or stopSelf();
                                }
                            }
                        });
                playerNotificationManager.setPlayer(player);
            }
            return START_STICKY;
        }

        @Override
        public void onDestroy() {
            player.release();
            player=null;
            super.onDestroy();
        }

        public void startPlayer(){

            player = new SimpleExoPlayer.Builder(this).build();

            player.addListener(this);

            dataSourceFactory = new DefaultDataSourceFactory(getApplicationContext(), "ExoplayerDemo");
            mediaSource =new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(streamUrl));
            player.prepare(mediaSource);
            player.setPlayWhenReady(true);
        }

        private void startForeground() {
            String channelId;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channelId =    createNotificationChannel("my_service", "My Background Service");
            } else {
                // If earlier version channel ID is not used
                // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
                channelId="";
            }

            Notification.Builder notificationBuilder = new Notification.Builder(this, channelId);
            Notification notification = notificationBuilder.setOngoing(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .build();
            startForeground(101, notification);
        }

        @RequiresApi(Build.VERSION_CODES.O)
        private String createNotificationChannel( String channelId,  String channelName){
       NotificationChannel  chan = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
       chan.setLightColor(Color.BLUE);
         chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            NotificationManager service =  ( NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            service.createNotificationChannel(chan);
            return channelId;
        }

        public SimpleExoPlayer getPlayerInstance() {
            if (player == null) {
                startPlayer();
            }
            return player;
        }

        public class LocalBinder extends Binder {
            public BackgroundService getService() {
                return BackgroundService.this;
            }
        }
    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题