如何在wowza服务器上发送实时流媒体时在SD卡中存储视频

时间:2014-07-19 05:26:23

标签: android video wowza

我正试图在wowza服务器上发送实时流媒体时将视频存储在SD卡中。我正在向wowza服务器发送成功的实时视频,但我无法将相应的视频存储到SD卡。I am using this library to send video to wowza sever

surfaceView=(SurfaceView) findViewById(R.id.surface);
    myChronometer = (Chronometer) findViewById(R.id.chronometer1);
    chat32=(Button) findViewById(R.id.chat32);
    chatedit=(EditText) findViewById(R.id.chatedit);
    send=(Button) findViewById(R.id.send);

    chatlist=(ListView) findViewById(R.id.camerachatlist);
    chat32.setOnClickListener(this);

    mButtonVideo = (Button) findViewById(R.id.video);
    mButtonSave = (Button) findViewById(R.id.save);
    mButtonStart = (Button) findViewById(R.id.start);
    mButtonFlash = (Button) findViewById(R.id.flash);
    mButtonCamera =(Button) findViewById(R.id.camera);
    mButtonSettings = (Button) findViewById(R.id.settings);
    mSurfaceView = (SurfaceView) findViewById(R.id.surface);
    mEditTextURI = (EditText) findViewById(R.id.uri);
    mEditTextUsername = (EditText) findViewById(R.id.username);
    mEditTextPassword = (EditText) findViewById(R.id.password);
    mTextBitrate = (TextView) findViewById(R.id.bitrate);
    mLayoutVideoSettings = (FrameLayout) findViewById(R.id.video_layout);
    mLayoutServerSettings = (FrameLayout) findViewById(R.id.server_layout);
    mRadioGroup = (RadioGroup) findViewById(R.id.radio);
    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);

    mRadioGroup.setOnCheckedChangeListener(this);
    mRadioGroup.setOnClickListener(this);

    mButtonStart.setOnClickListener(this);
    mButtonSave.setOnClickListener(this);
    mButtonFlash.setOnClickListener(this);
    mButtonCamera.setOnClickListener(this);
    mButtonVideo.setOnClickListener(this);
    mButtonSettings.setOnClickListener(this);
    mButtonFlash.setTag("off");

    SharedPreferences mPrefs = PreferenceManager
            .getDefaultSharedPreferences(VideoStream.this);
    if (mPrefs.getString("uri", null) != null)
        mLayoutServerSettings.setVisibility(View.GONE);
    mEditTextURI.setText(mPrefs.getString("uri",
            getString(R.string.default_stream)));
    System.out.println("text get from edittext" + mEditTextURI.getText());

    mEditTextPassword.setText(mPrefs.getString("password", "********"));
    System.out.println("text get from edittext"
            + mEditTextPassword.getText());

    mEditTextUsername.setText(mPrefs.getString("username", "*******"));
    System.out.println("text get from edittext"
            + mEditTextUsername.getText());

    // Configures the SessionBuilder
    SessionBuilder sessionbuilder = SessionBuilder.getInstance();

    mSession = SessionBuilder.getInstance().setCallback(VideoStream.this)
            .setContext(getApplicationContext())
            .setAudioEncoder(SessionBuilder.AUDIO_AAC)
            .setAudioQuality(new AudioQuality(8000, 16000))
            .setVideoEncoder(SessionBuilder.VIDEO_H264)
            .setSurfaceView(mSurfaceView).setPreviewOrientation(0)


            .build();

    // Configures the RTSP client
    mClient = new RtspClient();
    mClient.setSession(mSession);

    mClient.setCallback(VideoStream.this);

    System.out.println("helllllllloooo");




    // Use this to force streaming with the MediaRecorder API
    mSession.getVideoTrack().setStreamingMethod(
            MediaStream.MODE_MEDIARECORDER_API);

    // Use this to stream over TCP, EXPERIMENTAL!
    mClient.setTransportMode(RtspClient.TRANSPORT_TCP);

    // Use this if you want the aspect ratio of the surface view to
    // respect the aspect ratio of the camera preview
    mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);

    mSurfaceView.getHolder().addCallback(this);

    selectQuality();

}

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
    System.out.println("@@@@@@@@@@@@@@ onCheckedChanged");
    mLayoutVideoSettings.setVisibility(View.GONE);
    mLayoutServerSettings.setVisibility(View.VISIBLE);
    selectQuality();
}

// =================================================================
// on click

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.start:
        mLayoutServerSettings.setVisibility(View.GONE);
        toggleStream();
        break;
    case R.id.flash:
        if (mButtonFlash.getTag().equals("on")) {
            mButtonFlash.setTag("off");
            mButtonFlash
                    .setBackgroundResource(R.drawable.ic_flash_on_holo_light);
        } else {
            mButtonFlash
                    .setBackgroundResource(R.drawable.ic_flash_off_holo_light);
            mButtonFlash.setTag("on");
        }
        mSession.toggleFlash();
        break;
    case R.id.camera:
        mSession.switchCamera();
        break;
    case R.id.settings:
        if (mLayoutVideoSettings.getVisibility() == View.GONE
                && mLayoutServerSettings.getVisibility() == View.GONE) {
            mLayoutServerSettings.setVisibility(View.VISIBLE);
        } else {
            mLayoutServerSettings.setVisibility(View.GONE);
            mLayoutVideoSettings.setVisibility(View.GONE);
        }
        break;
    case R.id.video:
        mRadioGroup.clearCheck();
        mLayoutServerSettings.setVisibility(View.GONE);
        mLayoutVideoSettings.setVisibility(View.VISIBLE);
        break;
    case R.id.save:
        mLayoutServerSettings.setVisibility(View.GONE);
        break;
    case R.id.chat32:
        chatedit.setVisibility(View.VISIBLE);
        send.setVisibility(View.VISIBLE);
        break;
    case R.id.send: 
        chatlist.setVisibility(View.VISIBLE);
    }
}

// ===================================================

@Override
public void onDestroy() {
    super.onDestroy();
    mClient.release();
    mSession.release();
    mSurfaceView.getHolder().removeCallback(this);
}

private void selectQuality() {
    System.out.println("@@@@@@@@@@@@@@ selectQuality");
    int id = mRadioGroup.getCheckedRadioButtonId();
    RadioButton button = (RadioButton) findViewById(id);
    if (button == null)
        return;

    String text = button.getText().toString();

    System.out.println("text " + text);
    Pattern pattern = Pattern.compile("(\\d+)x(\\d+)\\D+(\\d+)\\D+(\\d+)");
    Matcher matcher = pattern.matcher(text);

    matcher.find();
    int width = Integer.parseInt(matcher.group(1));
    int height = Integer.parseInt(matcher.group(2));
    int framerate = Integer.parseInt(matcher.group(3));
    int bitrate = Integer.parseInt(matcher.group(4)) * 1000;

    mSession.setVideoQuality(new VideoQuality(width, height, framerate,
            bitrate));
    Toast.makeText(this, ((RadioButton) findViewById(id)).getText(),
            Toast.LENGTH_SHORT).show();

    Log.d(TAG, "Selected resolution: " + width + "x" + height);
}

private void enableUI() {
    System.out.println("@@@@@@@@@@@@@@ logError");
    mButtonStart.setEnabled(true);
    mButtonCamera.setEnabled(true);
}

// Connects/disconnects to the RTSP server and starts/stops the stream
public void toggleStream() {
    mProgressBar.setVisibility(View.VISIBLE);
    if (!mClient.isStreaming()) {
        String ip, port, path;

        // We save the content user inputs in Shared Preferences
        SharedPreferences mPrefs = PreferenceManager
                .getDefaultSharedPreferences(VideoStream.this);
        Editor editor = mPrefs.edit();
        editor.putString("uri", "********");
        editor.putString("password", "***********");
        editor.putString("username", "********");
        editor.commit();

        // String ip, port, path;

        // We parse the URI written in the Editext
        Pattern uri = Pattern.compile("rtsp://(.+):(\\d+)/(.+)");
        Matcher m = uri.matcher(AppConfig.STREAM_URL);
        m.find();
        ip = m.group(1);
        port = m.group(2);
        path = m.group(3);

        System.out.println("ip " + ip);

        System.out.println("port " + port);
        System.out.println("path " + path);

        /*
         * // We parse the URI written in the Editext Pattern uri =
         * Pattern.compile("rtsp://(.+):?(\\d*)/(.+)"); Matcher m =
         * uri.matcher(mEditTextURI.getText()); m.find(); ip = m.group(1);
         * port = m.group(2); path = m.group(3);
         * System.out.println("path is "+path);
         * 
         * System.out.println("port is "+port);
         * System.out.println("ip is "+ip);
         */

        mClient.setCredentials(AppConfig.PUBLISHER_USERNAME,
                AppConfig.PUBLISHER_PASSWORD);
        mClient.setServerAddress(ip, Integer.parseInt(port));
        mClient.setStreamPath("/" + path);


        mClient.startStream();
          fileUri = getOutputMediaFileUri();
        // Start camera preview
        mSession.startPreview();

    } else {
        // Stops the stream and disconnects from the RTSP server
        mClient.stopStream();

        // stop camera preview
        mSession.stopPreview();
    }
}

private void logError(final String msg) {
    System.out.println("@@@@@@@@@@@@@@ logError");
    final String error = (msg == null) ? "Error unknown" : msg;
    // Displays a popup to report the eror to the user
    AlertDialog.Builder builder = new AlertDialog.Builder(VideoStream.this);
    builder.setMessage(msg).setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                }
            });
    AlertDialog dialog = builder.create();
    dialog.show();
}

@Override
public void onBitrateUpdate(long bitrate) {
    System.out.println("@@@@@@@@@@@@@@ onBitrateUpdate");
    mTextBitrate.setText("" + bitrate / 1000 + " kbps");
}

@Override
public void onPreviewStarted() {

    System.out.println("@@@@@@@@@@@@@@ onPreviewStarted");
    if (mSession.getCamera() == CameraInfo.CAMERA_FACING_FRONT) {
        mButtonFlash.setEnabled(false);
        mButtonFlash.setTag("off");
        mButtonFlash.setBackgroundResource(R.drawable.ic_flash_on_holo_light);
    } else {
        mButtonFlash.setEnabled(true);
    }
}

@Override
public void onSessionConfigured() {
    System.out.println(" @@@@@@@@@@@@@@ onSessionConfigured");

}

@Override
public void onSessionStarted() {
    System.out.println("onSessionStarted");
    enableUI();
    mButtonStart.setBackgroundResource(R.drawable.record_pressed);
    myChronometer.setVisibility(View.VISIBLE);
    startTimer();
    mProgressBar.setVisibility(View.GONE);
    chat32.setVisibility(View.VISIBLE);

}

private void startTimer() {
    // TODO Auto-generated method stub
    myChronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
    myChronometer.start();
}

@Override
public void onSessionStopped() {
    System.out.println(" @@@@@@@@@@@@@@ onSessionStopped");
    enableUI();
    mButtonStart.setBackgroundResource(R.drawable.record_stop);
    mButtonStart.setBackgroundResource(R.drawable.record_stop);
    stopTimer();
    chat32.setVisibility(View.INVISIBLE);
    chatedit.setVisibility(View.INVISIBLE);
    send.setVisibility(View.INVISIBLE);
    mProgressBar.setVisibility(View.GONE);
}

private void stopTimer() {
    // TODO Auto-generated method stub
    myChronometer.setBase(SystemClock.elapsedRealtime());
    myChronometer.stop();
       showElapsedTime();
}

private void showElapsedTime() {
    // TODO Auto-generated method stub
      long elapsedMillis = SystemClock.elapsedRealtime()
                - myChronometer.getBase();
        Toast.makeText(VideoStream.this,
                "Elapsed milliseconds: " + elapsedMillis, Toast.LENGTH_SHORT).show();
}

@Override
public void onSessionError(int reason, int streamType, Exception e) {
    System.out.println(" @@@@@@@@@@@@@@ onSessionError");
    mProgressBar.setVisibility(View.GONE);
    switch (reason) {
    case Session.ERROR_CAMERA_ALREADY_IN_USE:
        break;
    case Session.ERROR_CAMERA_HAS_NO_FLASH:
        mButtonFlash.setBackgroundResource(R.drawable.ic_flash_on_holo_light);
        mButtonFlash.setTag("off");
        break;
    case Session.ERROR_INVALID_SURFACE:
        break;
    case Session.ERROR_STORAGE_NOT_READY:
        break;
    case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
        VideoQuality quality = mSession.getVideoTrack().getVideoQuality();
        logError("The following settings are not supported on this phone: "
                + quality.toString() + " " + "(" + e.getMessage() + ")");
        e.printStackTrace();
        return;
    case Session.ERROR_OTHER:
        break;
    }

    if (e != null) {
        logError(e.getMessage());
        e.printStackTrace();
    }
}

@Override
public void onRtspUpdate(int message, Exception e) {
    System.out.println(" @@@@@@@@@@@@@@ onRtspUpdate");
    switch (message) {
    case RtspClient.ERROR_CONNECTION_FAILED:
    case RtspClient.ERROR_WRONG_CREDENTIALS:
        mProgressBar.setVisibility(View.GONE);
        enableUI();
        logError(e.getMessage());
        e.printStackTrace();
        break;
    }
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    System.out.println(" @@@@@@@@@@@@@@ surfaceChanged");

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    mSession.startPreview();
    System.out.println(" @@@@@@@@@@@@@@ surfaceCreated");
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    mClient.stopStream();
    System.out.println(" @@@@@@@@@@@@@@ surfaceDestroyed");
}



}

1 个答案:

答案 0 :(得分:0)

你可以试试这个,

//来自图库的视频

    Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(
                Intent.createChooser(intent, "Select Video"),
                SELECT_VIDEO);

//来自相机的视频

        state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mVideoFileTemp = new File(Environment
                    .getExternalStorageDirectory(),
                    "Nameofthefile");
        } else {
            mVideoFileTemp = new File(getApplicationContext()
                    .getFilesDir(), "Nameofthefile");
        }
        intent = new Intent(
                android.provider.MediaStore.ACTION_VIDEO_CAPTURE);

        try {
            Uri mImageCaptureUri = null;
            // String state = Environment.getExternalStorageState();
            if (mVideoFileTemp == null) {
                System.out.println("no file found");
            } else {
                System.out.println("file found");}
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                mImageCaptureUri = Uri.fromFile(mVideoFileTemp);
            } else {
                mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
            }
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                    mImageCaptureUri);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, SELECT_CAMERA_VIDEO_REQUEST);
        } catch (ActivityNotFoundException e) {

            Log.d("Tag", "cannot take video", e);
        }

    @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {


        if (requestCode == SELECT_VIDEO && resultCode == Activity.RESULT_OK
                && null != data) {

            Uri selectedVideo = data.getData();
            String[] filePathColumn = { MediaStore.Video.Media.DATA };
            Cursor cursor = getApplicationContext().getContentResolver()
                    .query(selectedVideo, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String videoPath = cursor.getString(columnIndex);
            cursor.close();
            videoFile = new File(videoPath);
            bitmap_postImage = ThumbnailUtils.createVideoThumbnail(
                    videoPath, Thumbnails.MICRO_KIND);
            setImagePreview(bitmap_postImage);

        }

        if (requestCode == SELECT_CAMERA_VIDEO_REQUEST
                && resultCode == Activity.RESULT_OK) {

            videoFile = mVideoFileTemp;

            bitmap_postImage = ThumbnailUtils.createVideoThumbnail(
                    videoFile.getPath(), Thumbnails.MICRO_KIND);
            setImagePreview(bitmap_postImage);
        }
    }
}