码迷,mamicode.com
首页 > 移动开发 > 详细

android,Exoplayer实现视频播放器

时间:2018-11-14 15:31:35      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:top   onclick   uri   on()   java   screen   listener   sch   util   

bundle配置:
implementation ‘com.google.android.exoplayer:exoplayer-core:2.8.1‘
implementation ‘com.google.android.exoplayer:exoplayer-dash:2.8.1‘
implementation ‘com.google.android.exoplayer:exoplayer-ui:2.8.1‘
show Dialogfragment:
Fragment prev = getCurrentActivity().getFragmentManager().findFragmentByTag("VideoDialogFragment");
if(prev!=null){
DialogFragment diaFragment = (DialogFragment)prev;
diaFragment.dismiss();
}
VideoPlayerFragment dialogFragment = new VideoPlayerFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("videoUrl",视频地址);
bundle.putSerializable("videoName",视频名字);
dialogFragment.setArguments(bundle);
dialogFragment.show(getCurrentActivity().getFragmentManager(), "VideoDialogFragment");

DialogFragment:
public class VideoPlayerFragment extends DialogFragment {
    private ImageView screenImageView;
    private ImageView changeVoiceView;
    private TextView textVideoName;
    private LinearLayout mainVideoLayout;
    private LinearLayout videoLayout;
    private Window window;
    private Dialog dialog;

    private String videoUrl = null;
    private String videoName = null;
    private boolean isAllScreen = false;
    private boolean isOpenSound = true;
    private boolean isVideoMode = false;
    private int resumeWindow;
    private long resumePosition;
    private int videoScreenWidth;
    private int videoScreenHeight;

    private static Handler handler = new Handler();
    private SimpleExoPlayerView simpleExoPlayerView;
    private BandwidthMeter bandwidthMeter;
    private TrackSelection.Factory videoTrackSelectionFactory;
    private TrackSelector trackSelector;
    private SimpleExoPlayer player;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initPlayer();
    }

    private void initPlayer() {
        Common.silentSwitch(true);
        bandwidthMeter = new DefaultBandwidthMeter();//创建带宽
        videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);//创建轨道工厂
        trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);//创建轨道选择器实例
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.VideoTheme);
        if (ScreenUtils.isLandscape()) {
            videoScreenWidth = 900;
            videoScreenHeight = 620;
        } else {
            videoScreenWidth = 880;
            videoScreenHeight = 1564;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_exo_player, container);
        Bundle bundle = getArguments();
        if (bundle != null) {
            videoUrl = (String) bundle.getSerializable("videoUrl");
            videoName = (String) bundle.getSerializable("videoName");
            isVideoMode = (Boolean) bundle.getSerializable("isVideoMode");
        }

        dialog = getDialog();
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);

        window = dialog.getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = videoScreenWidth;
        lp.height = videoScreenHeight;
        window.setAttributes(lp);

        initView(view);
        openPlayer(view);
        startPlayer();
        return view;
    }

    private void initView(View view) {
        simpleExoPlayerView = (SimpleExoPlayerView) view.findViewById(R.id.simpleExoPlayerView);
        screenImageView = (ImageView) view.findViewById(R.id.btnAllScreen);
        mainVideoLayout = (LinearLayout) view.findViewById(R.id.mainVideoLayout);
        videoLayout = (LinearLayout) view.findViewById(R.id.videoLayout);
        textVideoName = (TextView) view.findViewById(R.id.videoName);
        if (!TextUtils.isEmpty(videoName)) {
            textVideoName.setText("当前正在播放:" + videoName);
        }
        if (isVideoMode) {
            screenImageView.setEnabled(false);
        } else {
            screenImageView.setEnabled(true);
        }
        changeVoiceView = (ImageView) view.findViewById(R.id.btnChangeVoice);
        changeVoiceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isOpenSound) {
                    changeVoiceView.setImageResource(R.drawable.mute_btn);
                    Common.silentSwitch(isOpenSound);
                    isOpenSound = false;

                } else {
                    changeVoiceView.setImageResource(R.drawable.voice_btn);
                    Common.silentSwitch(isOpenSound);
                    isOpenSound = true;
                }
            }
        });
        screenImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAllScreen) {
                    window = dialog.getWindow();
                    //获得窗体的属性
                    WindowManager.LayoutParams lp = window.getAttributes();
                    lp.gravity = Gravity.CENTER;
                    lp.width = videoScreenWidth;
                    lp.height = videoScreenHeight;
                    window.setAttributes(lp);
                    screenImageView.setImageResource(R.drawable.allscreen_btn);
                    //videoLayout.setLayoutParams(new FrameLayout.LayoutParams(1000, 600));
                    isAllScreen = false;
                } else {
                    screenImageView.setImageResource(R.drawable.cancelscreen_btn);
                    window = dialog.getWindow();
                    //获得窗体的属性
                    WindowManager.LayoutParams lp = window.getAttributes();
                    lp.gravity = Gravity.CENTER;
                    lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
                    window.setAttributes(lp);
                    //videoLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT));
                    isAllScreen = true;
                }
            }
        });
    }

    private void openPlayer(View view) {
        //创建播放器
        player = ExoPlayerFactory.newSimpleInstance(view.getContext(), trackSelector);
        //创建加载数据的工厂
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(view.getContext(),
                Util.getUserAgent(view.getContext(), "com.reactnativedemo"), (TransferListener<? super DataSource>) bandwidthMeter);

        //创建解析数据的工厂
        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
        //传入Uri、加载数据的工厂、解析数据的工厂,就能创建出MediaSource
        String url = videoUrl;
        Uri mp4VideoUri = Uri.parse(url);
        MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri,
                dataSourceFactory, extractorsFactory, null, null);
        //循环播放
        LoopingMediaSource loopingMediaSource = new LoopingMediaSource(videoSource);
        player.prepare(loopingMediaSource);
        player.addListener(eventListener);
        player.setPlayWhenReady(true);
    }

    private ExoPlayer.EventListener eventListener = new ExoPlayer.EventListener() {
        @Override
        public void onTimelineChanged(Timeline timeline, Object o, int i) {

        }

        @Override
        public void onTracksChanged(TrackGroupArray trackGroupArray, TrackSelectionArray trackSelectionArray) {

        }

        @Override
        public void onLoadingChanged(boolean b) {

        }

        @Override
        public void onPlayerStateChanged(boolean b, int i) {

        }

        @Override
        public void onRepeatModeChanged(int i) {

        }

        @Override
        public void onShuffleModeEnabledChanged(boolean b) {

        }

        @Override
        public void onPlayerError(ExoPlaybackException e) {
            if (player != null) {
                player.stop();
                player.release();
                player = null;
            }
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            Fragment prev = getFragmentManager().findFragmentByTag("VideoDialogFragment");
            if (prev != null) {
                ft.remove(prev);
            }
        }

        @Override
        public void onPositionDiscontinuity(int i) {

        }

        @Override
        public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {

        }

        @Override
        public void onSeekProcessed() {
        }
    };

    private void startPlayer() {
        simpleExoPlayerView.setPlayer(player);
        //player.setPlayWhenReady(true);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (player != null && player.getCurrentPosition() > 0) {
            player.setPlayWhenReady(true);
            player.seekTo(resumePosition);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (player != null && player.getPlayWhenReady()) {
            resumeWindow = player.getCurrentWindowIndex();
            resumePosition = Math.max(0, player.getContentPosition());
            player.setPlayWhenReady(false);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //释放播放器
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        silentSwitch(false);
    }
}

  开关静音:

public static void silentSwitch(boolean isOpenVoice) {
try {
AudioManager mAudioManager = (AudioManager) context.getSystemService(Service.AUDIO_SERVICE);
if (mAudioManager != null) {
if (isOpenVoice) {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
} else {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
}
} catch (Exception e) {

}
}
作者原创,转载请注明原文地址。

android,Exoplayer实现视频播放器

标签:top   onclick   uri   on()   java   screen   listener   sch   util   

原文地址:https://www.cnblogs.com/candyzhmm/p/9957928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!