Android 비디오 자막 Subtitle 과 가로 세로 화면 전환 예제 구현

시스템 이 자체 적 으로 가지 고 있 는 VideoView 의 일부 영상 형식 은 지원 되 지 않 는 다.그러면 우 리 는 제3자 가 실현 한 VideoView 대체 시스템 으로 영상 을 재생 할 수 있다.비교적 유행 하 는 것 은ijkplayer,vitamio이다.
최근 에는 동 영상 에 자막 을 넣 어야 한 다 는 수요 가 있 는데,사실 간단 하 다.자막 이 자주 사용 하 는 형식 은 srt 입 니 다.실제 텍스트 입 니 다.해석 한 다음 에 시간 에 따라 보 여 드 리 면 OK 입 니 다.그리고 회전 버튼 이 꺼 져 도 방향 감지 기 에 따라 가로 세로 화면 전환 이 가능 하 다 는 것 이다.
본 고 는 시스템 VideoView 를 사용 한 다음 에 sd 카드 에 있 는 동 영상 을 재생 하여 프 리 젠 테 이 션(소스 코드 에 f2.mp4 와 f2.srt 가 있 고 실행 할 때 sd 카드 로 복사 하면 됩 니 다)을 보 여 줍 니 다.다음은 소스 코드 를 간단하게 소개 합 니 다.
MainActivity 는 자막 을 표시 하고 가로 세로 화면 을 어떻게 전환 하 는 지 포함 합 니 다.

public class SubtitleActivity extends Activity implements View.OnClickListener,OnTouchListener{
	private VideoView videoView ;
	TextView tvSrt, mCurrentTime,mTotalTime,resolution_switch,mediacontroller_file_name;
	ImageView mediacontroller_play_pause,switch_screen;
	private SeekBar progress_seekbar;
	private AudioManager mAM;
	private long totalDuration;
	private boolean mShowing = true, mDragging,isResolution;
	private static final int PARSE_SRT = 0;
	private static final int FADE_OUT = 1;
	private static final int SHOW_PROGRESS = 2;
	private static final int CHANGE_VIDEOVIEW_BG = 3;
	private static final int SCREEN_ORIENTATION_USER = 4;
	private static final int sDefaultTimeout = 3000;
	private RelativeLayout videoview_layout, mMediaController;
	private ListView resolution_listview;
	private boolean isPortraint = true;
	private static int LockScreen = -1;//             ,0   1   
	private int screenWidth,videoViewHeight;
	List<VideoPathObject> videopathList=new ArrayList<VideoPathObject>();
	Handler mHandler=new Handler(){
		public void handleMessage(Message msg){
			long pos;
			switch (msg.what) {
				case PARSE_SRT:
					SrtParser.showSRT(videoView,tvSrt) ;
				//  500ms    showSRT(),            
					mHandler.sendEmptyMessageDelayed(0, 500);
					break;
				case FADE_OUT:
					showOrHideController();
					break;
				case SHOW_PROGRESS:
					pos = setControllerProgress();
					if (!mDragging && mShowing) {
						msg = obtainMessage(SHOW_PROGRESS);
					sendMessageDelayed(msg, 1000 - (pos % 1000));
					}
					break;
				case CHANGE_VIDEOVIEW_BG:
					videoView.setBackgroundColor(0x00000000);
					break;
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_subtitle);
		videoView = (VideoView)this.findViewById(R.id.videoView );
		mAM = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		screenWidth = APPApplication.screenWidth;
		videoViewHeight = screenWidth * 9 / 16;
		tvSrt = (TextView)findViewById(R.id.srt);//          
	mediacontroller_file_name= (TextView)findViewById(R.id.mediacontroller_file_name);
//		String[]splitStr=Constant.videoUrl1.split("/");
//		mediacontroller_file_name.setText(splitStr[splitStr.length-1]);
		mTotalTime = (TextView) findViewById(R.id.mediacontroller_time_total);
		mCurrentTime = (TextView) findViewById(R.id.mediacontroller_time_current);
		resolution_switch = (TextView) findViewById(R.id.resolution_switch);
	mediacontroller_play_pause = (ImageView) findViewById(R.id.mediacontroller_play_pause);
		switch_screen = (ImageView) findViewById(R.id.switch_screen);
		videoview_layout = (RelativeLayout) findViewById(R.id.videoview_layout);
		mediacontroller_play_pause.setOnClickListener(this);
		progress_seekbar = (SeekBar) findViewById(R.id.mediacontroller_seekbar);
		videoview_layout = (RelativeLayout) findViewById(R.id.videoview_layout);
		mMediaController = (RelativeLayout) findViewById(R.id.media_controller);
		resolution_listview = (ListView) findViewById(R.id.resolution_listview);
		resolution_switch.setOnClickListener(this);
		videoView.setOnTouchListener(this);
		progress_seekbar.setOnSeekBarChangeListener(mSeekListener);
		LayoutParams params = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, videoViewHeight);
		videoview_layout.setLayoutParams(params);
		try {
	// 1        true,0         false
	// Settings.System.getInt(mContext.getContentResolver(),Settings.System.ACCELEROMETER_ROTATION,0);
		LockScreen = Settings.System.getInt(getContentResolver(),
					Settings.System.ACCELEROMETER_ROTATION);
		} catch (SettingNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		String rawUri = "android.resource://" + getPackageName() + "/" + R.raw.renwei;
		Uri uri = Uri.parse(Constant.videoUrl1);
		//       
// videoView.setMediaController(new MediaController(this));
		//      
		videoView.setOnCompletionListener( new MyPlayerOnCompletionListener());
		videoView.setOnPreparedListener(new OnPreparedListener() {
			//@Override
			public void onPrepared(MediaPlayer mp) {
				totalDuration=videoView.getDuration();
				if (mTotalTime != null)
			mTotalTime.setText("/"+generateTime(totalDuration));
			}
		});
		//      
		videoView.setVideoURI(uri);
		//      
		videoView.start();
		SrtParser.parseSrt(this);
		SrtParser.showSRT(videoView,tvSrt) ;
		mHandler.sendEmptyMessageDelayed(0, 500);
		initVideoResolution();
	}
	private void initVideoResolution(){
		VideoPathObject object1=new VideoPathObject();
		object1.videoStatus="  ";
		videopathList.add(object1);
		VideoPathObject object2=new VideoPathObject();
		object2.videoStatus="  ";
		videopathList.add(object2);
		VideoPathObject object3=new VideoPathObject();
		object3.videoStatus="  ";
		videopathList.add(object3);
		switchResolution(videopathList);
	}
	class MyPlayerOnCompletionListener implements MediaPlayer.OnCompletionListener {
		@Override
		public void onCompletion(MediaPlayer mp) {
	Toast.makeText( SubtitleActivity.this, "     ", Toast.LENGTH_SHORT).show();
		}
	}
	private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
		public void onStartTrackingTouch(SeekBar bar) {
			mDragging = true;
			mHandler.removeMessages(SHOW_PROGRESS);
			mAM.setStreamMute(AudioManager.STREAM_MUSIC, true);
		}
		public void onProgressChanged(SeekBar bar, int progress,
		 boolean fromuser) {
			if (!fromuser)
				return;
			int newposition = (int)(totalDuration * progress) / 1000;
			String time = generateTime(newposition);
			videoView.seekTo(newposition);
			mCurrentTime.setText(time);
		}
		public void onStopTrackingTouch(SeekBar bar) {
			videoView.seekTo(((int)totalDuration * bar.getProgress()) / 1000);
			hideMediaController(sDefaultTimeout);
			mAM.setStreamMute(AudioManager.STREAM_MUSIC, false);
			mDragging = false;
			mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
		}
	};
	private void switchResolution(final List<VideoPathObject> videopathList) {
		resolution_switch
	.setText(videopathList.get(videopathList.size() - 1).videoStatus);
		mediacontroller_play_pause.setImageResource(R.drawable.player_play);
		final ResolutionAdapter adapter = new ResolutionAdapter(videopathList,
				SubtitleActivity.this);
		resolution_listview.setAdapter(adapter);
		resolution_listview
		.setOnItemClickListener(new AdapterView.OnItemClickListener() {
		@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
											int position, long arg3) {
				// TODO Auto-generated method stub
//				// currentPosition = videoView.getCurrentPosition();
//				currentPosition = videoView.getCurrentPosition();
//				Log.d("gaolei", "currentPosition---------1------"
//								+ currentPosition);
				VideoPathObject pathObject = videopathList
								.get(position);
////				playVideo(pathObject.videoUrl);
//				adapter.changePosition(position);
				resolution_switch.setText(pathObject.videoStatus);
				resolution_listview.setVisibility(View.GONE);
					}
				});
	}
	public void showOrHideController() {
		if (mShowing) {
			mHandler.removeMessages(SHOW_PROGRESS);
			mHandler.removeMessages(FADE_OUT);
			mMediaController.setVisibility(View.GONE);
			resolution_listview.setVisibility(View.GONE);
			mShowing = false;
		} else {
			mHandler.sendEmptyMessage(SHOW_PROGRESS);
			mMediaController.setVisibility(View.VISIBLE);
			hideMediaController(sDefaultTimeout);
			mShowing = true;
		}
	}
	public void hideMediaController(int sDefaultTimeout) {
		mHandler.sendEmptyMessageDelayed(FADE_OUT, sDefaultTimeout);
	}
	private long setControllerProgress() {
		if (videoView == null || mDragging)
			return 0;
		int position = videoView.getCurrentPosition();
		if (progress_seekbar != null) {
			if (totalDuration > 0) {
				long pos = 1000L * position / totalDuration;
				// Log.d("gaolei", "progress--------------" + pos);
				progress_seekbar.setProgress((int) pos);
			}
			int percent = videoView.getBufferPercentage();
			progress_seekbar.setSecondaryProgress(percent * 10);
		}
		if (mCurrentTime != null)
			mCurrentTime.setText(generateTime(position));
		return position;
	}
	private static String generateTime(long position) {
		int totalSeconds = (int) (position / 1000);
		int seconds = totalSeconds % 60;
		int minutes = (totalSeconds / 60) % 60;
		int hours = totalSeconds / 3600;
		if (hours > 0) {
			return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes,
					seconds).toString();
		} else {
			return String.format(Locale.US, "%02d:%02d", minutes, seconds)
					.toString();
		}
	}
	private void updatePausePlay() {
		if (videoView.isPlaying()) {
			videoView.pause();
			mediacontroller_play_pause
					.setImageResource(R.drawable.player_pause);
		} else {
			videoView.start();
			mediacontroller_play_pause.setImageResource(R.drawable.player_play);
		}
	}
	public void showResolution(View view) {
		if (!isResolution) {
			resolution_listview.setVisibility(View.VISIBLE);
			isResolution = true;
		} else {
			resolution_listview.setVisibility(View.GONE);
			isResolution = false;
		}
	}
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			changeToFullScreen();
			Log.d("gaolei", "ORIENTATION_LANDSCAPE-------------");
		}
		if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			changeToSmallScreen();
			Log.d("gaolei", "ORIENTATION_PORTRAIT-------------");
		}
	}
	public void switchScreen(View view) {
		if (isPortraint) {
			handToFullScreen();
		} else {
			handToSmallScreen();
		}
	}
	public void handToSmallScreen() {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
		changeToSmallScreen();
		/**
		 *         ,  5      ,           
		 */
		autoSwitchScreenOrientation();
	}
	public void handToFullScreen() {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		changeToFullScreen();
		autoSwitchScreenOrientation();
	}
	private void changeToFullScreen() {
		isPortraint = false;
		LayoutParams params = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, APPApplication.screenWidth);
		videoview_layout.setLayoutParams(params);
		videoView.setLayoutParams(params);
		WindowManager.LayoutParams windowparams = getWindow().getAttributes();
		windowparams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
		getWindow().setAttributes(windowparams);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
		switch_screen.setImageResource(R.drawable.player_switch_small);
	}
	private void changeToSmallScreen() {
		isPortraint = true;
		LayoutParams params = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, videoViewHeight);
		videoview_layout.setLayoutParams(params);
		videoView.setLayoutParams(params);
		WindowManager.LayoutParams windowparams = getWindow().getAttributes();
		windowparams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setAttributes(windowparams);
		getWindow()
				.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
		switch_screen.setImageResource(R.drawable.player_switch_big);
	}
	public void autoSwitchScreenOrientation() {
//		      ,5s         
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
			// TODO Auto-generated method stub
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
			Log.d("gaolei", "SCREEN_ORIENTATION_FULL_SENSOR");				}
		}, 5000);
	}
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN: {
				showOrHideController();
				break;
			}
		}
		return false;
	}
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch(view.getId()){
			case R.id.mediacontroller_play_pause:
				Log.d("gaolei", "mediacontroller_play_pause");
				updatePausePlay();
				break;
			case R.id.resolution_switch:
				resolution_listview.setVisibility(View.VISIBLE);
				break;
		}
	}
	public void jumpToMain(View view){
		startActivity(new Intent(this, MainActivity.class));
	}
	public void onRestart(){
		super.onRestart();
		videoView.start();
		mediacontroller_play_pause.setImageResource(R.drawable.player_play);
	}
	public void onStop(){
		super.onStop();
		videoView.pause();
		mediacontroller_play_pause.setImageResource(R.drawable.player_pause);
	}
}
SrtParser 는 자막 파일 을 해석 하 는 알고리즘 입 니 다.

public class SrtParser {
 public static ArrayList<SRT>srtList;
 public static int lastEndTime;
 /**
 *   SRT    
 *     
 */
 public static void parseSrt(Context context) {
 InputStream inputStream = null;
 try {
//  inputStream=context.getResources().openRawResource(R.raw.renwei2);
  inputStream = new FileInputStream(Constant.srtUrl1);
  // TODO Auto-generated catch block
  BufferedReader br = new BufferedReader(new InputStreamReader(
   inputStream,"GB2312"));
  String line = null;
  srtList = new ArrayList<SRT>();
  StringBuffer sb = new StringBuffer();
  while ((line = br.readLine()) != null) {
  // Log.d("gaolei", "br.readLine()-----------"+br.readLine());
  if (!line.equals("")) {
   Log.d("gaolei","line-------------------"+ line);
   sb.append(line).append("@");
   continue;
  }
  Log.d("gaolei", "sb.toString()-----------"+sb.toString());
  String[] parseStrs = sb.toString().split("@");
  //  if                        
  if (parseStrs.length < 3) {
   sb.delete(0, sb.length());//   ,              </i>
   continue;
  }
  SRT srt = new SRT();
  //          
  String timeTotime = parseStrs[1];
  int begin_hour = Integer.parseInt(timeTotime.substring(0, 2));
  int begin_mintue = Integer.parseInt(timeTotime.substring(3, 5));
  int begin_scend = Integer.parseInt(timeTotime.substring(6, 8));
  int begin_milli = Integer.parseInt(timeTotime.substring(9, 12));
  int beginTime = (begin_hour * 3600 + begin_mintue * 60 + begin_scend)
   * 1000 + begin_milli;
  int end_hour = Integer.parseInt(timeTotime.substring(17, 19));
  int end_mintue = Integer.parseInt(timeTotime.substring(20, 22));
  int end_scend = Integer.parseInt(timeTotime.substring(23, 25));
  int end_milli = Integer.parseInt(timeTotime.substring(26, 29));
  int endTime = (end_hour * 3600 + end_mintue * 60 + end_scend)
   * 1000 + end_milli;
  System.out.println("  :" + begin_hour + ":" + begin_mintue +
   ":"
   + begin_scend + ":" + begin_milli + "=" + beginTime
   + "ms");
  System.out.println("  :" + end_hour + ":" + end_mintue + ":"
   + end_scend + ":" + end_milli + "=" + endTime + "ms");
  //       
  String srtBody = "";
  //   1   ,   2    。
  for (int i = 2; i < parseStrs.length; i++) {
   srtBody += parseStrs[i]+ "
"; } // "
" srtBody = srtBody.substring(0, srtBody.length() - 1); // SRT srt.setBeginTime(beginTime); srt.setEndTime(endTime); srt.setSrtBody(new String(srtBody.getBytes(), "UTF-8")); srtList.add(srt); sb.delete(0, sb.length());// , } lastEndTime=srtList.get(srtList.size()-1).getEndTime(); br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 500ms () } public static void showSRT(VideoView videoView,TextView tvSrt) { // Log.d("gaolei", "srt_map.size()--------------"+srt_map.size()); int currentPosition = videoView.getCurrentPosition();//vv VideoView if(currentPosition>lastEndTime){ tvSrt.setVisibility(View.GONE); return; } for(int i=0;i<srtList.size();i++){ SRT srtbean =srtList.get(i); if (currentPosition > srtbean.getBeginTime() && currentPosition < srtbean.getEndTime()) { tvSrt.setText(srtbean.getSrtBody()); // , srtList.remove(i); break;// , } } } }
실행 효과 그림:


프로젝트 소스 코드,다운로드 클릭...
이상 의 안 드 로 이 드 는 영상 자막 자막 자막 자막 과 가로 세로 화면 전환 예 시 를 실현 하 는 것 이 바로 편집장 이 여러분 에 게 공유 한 모든 내용 입 니 다.여러분 께 참고 가 되 고 저희 도 많이 응원 해 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기