android自定义相机不工作?

时间:2014-01-29 12:41:45

标签: android

 public class Cemara extends Activity implements SurfaceHolder.Callback{

private Camera prCamera;
private SurfaceHolder prSurfaceHolder;
private SurfaceView prSurfaceView;
private int cMaxRecordDurationInMs = 15000;
private int rotated_angle =90;
private long cMaxFileSizeInBytes = 20971520;//20 Megabyte
private ToggleButton recordtogglebutton;
private TextView timeElapsed1;
private boolean prRecordInProcess;
private MediaRecorder prMediaRecorder;
private File prRecordedFile;
private String cVideoFilePath;
private Button p,l;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cemara);

    p=(Button)findViewById(R.id.button2);
    l=(Button)findViewById(R.id.button1);

    p.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        }
    });
    l.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        }
    });
    //create file in cache or in external storage  
    FileCache();

    prRecordInProcess = false;
    cVideoFilePath = android.os.Environment.getExternalStorageDirectory()+"/VRP/";

    prSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
    timeElapsed1 = (TextView) findViewById(R.id.timeElapsed);
    recordtogglebutton = (ToggleButton) findViewById(R.id.recordtogglebutton);

    prSurfaceHolder = prSurfaceView.getHolder();
    prSurfaceHolder.addCallback(this);
    prSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    prMediaRecorder = new MediaRecorder();
    recordtogglebutton.setOnCheckedChangeListener(checkedchangelistener);
}

private File cacheDir;
private void FileCache(){
    //Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"recording");
    else
        cacheDir=this.getCacheDir();

    if(!cacheDir.exists())
        cacheDir.mkdirs();

    File card_folder = new File(cacheDir,"cards");
    if(!card_folder.exists())
        card_folder.mkdirs();
}




private OnCheckedChangeListener checkedchangelistener =  new OnCheckedChangeListener(){

    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
        // TODO Auto-generated method stub
        /*pause player*/
        if(isChecked){
            System.out.println("start recording....");
            if(startRecording())
                // update current playback time every 500ms until stop
                timer.start();
            else
                Toast.makeText(Cemara.this, "Some error in Camera !!", Toast.LENGTH_SHORT).show();
        }
        /*play player*/
        else{
            System.out.println("stop recording......");
            stopRecording();
            timer.cancel();
            forwardscreen();
        }
    }};


    @Override
    public void surfaceChanged(SurfaceHolder _holder, int _format, int _width, int _height) {
        // TODO Auto-generated method stub
        try {
            prCamera.stopPreview();
            prCamera.setDisplayOrientation(rotated_angle);
            prCamera.setPreviewDisplay(_holder);
            prCamera.startPreview();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub

        /*open front camera*/
        CameraInfo cameraInfo = new CameraInfo(); 
        int cameraCount = Camera.getNumberOfCameras();
        if(cameraCount >1)
            for ( int camIdx = 0; camIdx < Camera.getNumberOfCameras(); camIdx++ ) { 
                Camera.getCameraInfo( camIdx, cameraInfo ); 
                if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT  ) { 
                    try { 
                        prCamera = Camera.open( camIdx ); 
                    } catch (RuntimeException e) { 
                        Log.i("Camera failed to open: ",e.getLocalizedMessage()); 
                    } 
                } 
            }else       
                prCamera = Camera.open();

        if (prCamera == null) {
            Toast.makeText(this, "Camera is not available!", Toast.LENGTH_SHORT).show();
            finish();
        }
    }


    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        if (prRecordInProcess) {
            stopRecording();
        }/* else {
        prCamera.stopPreview();
    }
    prMediaRecorder.release();
    prMediaRecorder = null;
    prCamera.release();
    prCamera = null;*/
    }


    private boolean startRecording() {
        prCamera.stopPreview();
        try {
            prCamera.unlock();
            prMediaRecorder.setCamera(prCamera);

            prMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            prMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            prMediaRecorder.setOrientationHint(rotated_angle);
            prMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            prMediaRecorder.setAudioEncoder(AudioEncoder.AMR_NB);
            prMediaRecorder.setVideoEncoder(VideoEncoder.MPEG_4_SP);
            prMediaRecorder.setMaxDuration(cMaxRecordDurationInMs);
            prMediaRecorder.setMaxFileSize(cMaxFileSizeInBytes);
            //prMediaRecorder.setAudioEncodingBitRate(25000);

            prRecordedFile = new File(cVideoFilePath + String.valueOf(System.currentTimeMillis()) +".mp4");
            prMediaRecorder.setOutputFile(prRecordedFile.getPath());
            prMediaRecorder.setPreviewDisplay(prSurfaceHolder.getSurface());
            prMediaRecorder.prepare();
            prMediaRecorder.start();

            prRecordInProcess = true;
            return true;

        } catch (IOException _le) {
            _le.printStackTrace();
            return false;
        }
    }

    private void stopRecording() {
        prMediaRecorder.stop();
        prMediaRecorder.reset();
        prMediaRecorder.release();
        timeElapsed1.setText("--:--");
        prRecordInProcess = false;
        prCamera.lock();
        prCamera.stopPreview();
        prCamera.release();
        prCamera =null;

        /*insert video information into database*/
        Date taken = new Date();
        ContentValues values = new ContentValues(10);
        values.put(Media.TITLE, prRecordedFile.getName());
        values.put(Media.DISPLAY_NAME, prRecordedFile.getName());
        values.put(Media.DATE_TAKEN, taken.getTime());
        values.put(Media.DATE_ADDED, taken.getTime());
        values.put(Media.DATE_MODIFIED, taken.getTime());
        values.put(Media.MIME_TYPE, "video/mp4");

        values.put(Media.BUCKET_ID, prRecordedFile.getParentFile().toString().toLowerCase());
        values.put(Media.BUCKET_DISPLAY_NAME, prRecordedFile.getParentFile().getName().toLowerCase());
        values.put(Media.SIZE, prRecordedFile.length());
        values.put(Media.DATA, prRecordedFile.getAbsolutePath());

        ContentResolver contentResolver = getApplicationContext().getContentResolver();
        Uri uri = contentResolver.insert(Media.EXTERNAL_CONTENT_URI, values);
        Log.i("ContentResolver---cemara", uri.toString());


    }

    /**
     * CountDownTimer using for counting elapsed time of media file
     */
    private CountDownTimer timer = new CountDownTimer(cMaxRecordDurationInMs, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            timeElapsed1.setText(countTime(millisUntilFinished));
        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
            stopRecording();
            forwardscreen();
        }
    };
    /**
     * Convert time from milliseconds into minutes and seconds, proper to media player
     * 
     * @param miliseconds   media content time in milliseconds
     * @return  time in format minutes:seconds
     */
    private String countTime(long miliseconds) {
        String timeInMinutes = new String();
        long minutes = miliseconds / 60000;
        long seconds = (miliseconds % 60000)/1000;
        timeInMinutes = minutes + ":" + (seconds<10?"0" + seconds:seconds);
        return timeInMinutes;
    }

这里是playvideo.java

public class PlayVideo extends Activity implements OnPreparedListener{
private String TAG = getClass().getSimpleName();
//private Button choose;
private ToggleButton playtogglebutton;
private TextView timeEnd, timeElapsed;
private ProgressBar progressBar;
private VideoView videoviewer;
private CountDownTimer timer;
private Bundle extra;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.play_video);

    extra = getIntent().getExtras();
    System.out.println(extra.size()+""+extra.getString("path"));
          playtogglebutton = (ToggleButton) findViewById(R.id.playtogglebutton);
    timeElapsed = (TextView) findViewById(R.id.timeElapsed);
    timeEnd = (TextView) findViewById(R.id.timeEnd);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    playtogglebutton.setOnCheckedChangeListener(checkedchangelistener);

videoviewer = (VideoView) findViewById(R.id.videoviewer);
    videoviewer.setVideoURI(Uri.parse(extra.getString("path")));
    videoviewer.requestFocus();
    videoviewer.setOnPreparedListener(PlayVideo.this);
}

private OnCheckedChangeListener checkedchangelistener =  new OnCheckedChangeListener(){

    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
        // TODO Auto-generated method stub
        /*pause player*/
        if(isChecked){
            System.out.println("player pause");
            playMedia(false);
        }
        /*play player*/
        else{
            System.out.println("player play");
            playMedia(true);
        }
    }};

    @Override
    public void onPrepared(MediaPlayer mp) {
        // TODO Auto-generated method stub
        Log.d(TAG, "media player preparing.......");
        mp.setLooping(true);


        // onSeekCompletionListener declaration
        mp.setOnSeekCompleteListener(new OnSeekCompleteListener() {
            // show current frame after changing the playback position
            @Override
            public void onSeekComplete(MediaPlayer mp) {
                if (!mp.isPlaying()) {
                    //playMedia(true);
                    System.out.println("inside the setOnSeekCompleteListener");
                    playMedia(false);
                }
                System.out.println("inside------ the setOnSeekCompleteListener");
                timeElapsed.setText(countTime(videoviewer.getCurrentPosition()));
            }
        });

        mp.setOnCompletionListener(null);
        // onBufferingUpdateListener declaration
        mp.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
            // show updated information about the buffering progress
            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.d(this.getClass().getName(), "percent: " + percent);
            }
        });

        int time = videoviewer.getDuration();
        int time_elapsed = videoviewer.getCurrentPosition();
        progressBar.setProgress(time_elapsed);

        // update current playback time every 500ms until stop
        timer = new CountDownTimer(time, 500) {

            @Override
            public void onTick(long millisUntilFinished) {
                timeElapsed.setText(countTime(videoviewer.getCurrentPosition()));
                float a = videoviewer.getCurrentPosition();
                float b = videoviewer.getDuration();
                progressBar.setProgress((int) (a / b * 100));
            }

            @Override
            public void onFinish() {
                stopMedia();
            }
        };


        timeEnd.setText(countTime(time));
        timeElapsed.setText(countTime(time_elapsed));
        playMedia(true);
    }

    /**
     * Convert time from milliseconds into minutes and seconds, proper to media player
     * 
     * @param miliseconds   media content time in milliseconds
     * @return  time in format minutes:seconds
     */
    public String countTime(int miliseconds) {
        String timeInMinutes = new String();
        int minutes = miliseconds / 60000;
        int seconds = (miliseconds % 60000)/1000;
        timeInMinutes = minutes + ":" + (seconds<10?"0" + seconds:seconds);
        return timeInMinutes;
    }

    /**
     * Start or Pause playback of media content
     * 
     * @param v View the touch event has been dispatched to
     */
    public void playMedia(boolean isplay) {

        if (isplay) {
            videoviewer.start();
            timer.start();

        } else {
            videoviewer.pause();
            timer.cancel();
        }

    }

    /**
     * Pause and rewind to beginning of the media content
     * 
     * @param v View the touch event has been dispatched to
     */
    public void stopMedia() {
        if (videoviewer.getCurrentPosition() != 0) {

            playtogglebutton.setChecked(true);

            videoviewer.pause();
            videoviewer.seekTo(0);
            timer.cancel();

            timeElapsed.setText(countTime(videoviewer.getCurrentPosition()));
            progressBar.setProgress(0);
        }
    }


    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        if(videoviewer != null)
            videoviewer.stopPlayback();
        if (timer != null) {
            timer.cancel();
        }
        super.onStop();
    }
  }



    private void forwardscreen(){
        Intent intent = new Intent(Cemara.this, PlayVideo.class);
        intent.putExtra("path", prRecordedFile.getAbsolutePath());
        startActivity(intent);
        finish();
    }
     }

logcat 我正在使用自定义相机进行视频录制,当用户点击切换按钮,定时器启动和视频录制播放时,它工作正常。在htc mobile ..,但是当我在索尼手机中运行我的应用程序时,我得到了不明白的执行并说相机不支持..,我是相机的相关错误,我做的请帮助...,谢谢你。

0 个答案:

没有答案