Xamarin-如何录制视频并将其保存到文件中

时间:2017-02-08 14:13:29

标签: android video xamarin xamarin.android

我正在尝试录制视频并将其保存到文件中,但在录制时我一直收到错误消息。代码是

using System;         
using Android.App;
using Android.OS;
using Android.Widget;
using Android.Media;
using System.Timers;
using Android.Content;
using System.IO;

namespace ShowHouseDemo2._1
{
    [Activity(Label = "VideoPage", Icon = "@drawable/icon")]
//Intent intent = GetInTent();
class VideoPage : Activity
{

    //Intent string Vid = Intent.GetStringExtra("VidSent");
    MediaRecorder recorder;
    Timer StartTimer;
    int StartCount = 0;
    protected override void OnCreate(Bundle bundle)
    {

        base.OnCreate(bundle);
        SetContentView(Resource.Layout.VidTakerPage);

        var video = FindViewById<VideoView>(Resource.Id.UserVid);
        //string  path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath.   "/UserVid4.mp4";
        // string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + ;
        var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
        var filename = Path.Combine(documents, "Write.txt");
        File.WriteAllText(filename, "Write this text into a file!");

        video.StopPlayback();


        recorder = new MediaRecorder();
        recorder.SetVideoSource(VideoSource.Camera);
        recorder.SetAudioSource(AudioSource.Mic);
        recorder.SetOutputFormat(OutputFormat.Default);
        recorder.SetVideoEncoder(VideoEncoder.Default);
        recorder.SetAudioEncoder(AudioEncoder.Default);
        recorder.SetOutputFile(filename);
        recorder.SetPreviewDisplay(video.Holder.Surface);
        recorder.Prepare();
        recorder.Start();

        timerStarted();
    }

    private void timerStarted()
    {
        base.OnResume();
        StartTimer = new Timer();
        StartTimer.Interval = 1000;
        StartTimer.Elapsed += delegate
        {
            while (StartCount < 10)
            {
                if (StartCount == 9)
                {
                    RunOnUiThread(() =>
                    {
                        Intent k = new Intent(this, typeof(TakeVideo));

                        this.StartActivity(k);
                    });
                }
                StartCount++;
            }
        };
    }
}
}

我得到的错误是:

Unhandled Exception: 
Java.IO.IOException: invalid preview surface.

我喜欢你能给我的任何帮助。如果您有任何问题,请询问

1 个答案:

答案 0 :(得分:2)

您需要实现表面回调界面(Android.Views.ISurfaceHolderCallback),并且只有在可用且有效时才开始使用ISurfaceHolder.Holder

您可以在VideoPage活动上执行此操作,即

[Activity(Label = "VideoPage", Icon = "@drawable/icon")]
public class VideoPage : Activity, Android.Views.ISurfaceHolderCallback

实现界面的三种方法(SurfaceDestroyedSurfaceCreatedSurfaceChanged),然后您可以通过VideoView.Holder.AddCallback分配回调:

var video = FindViewById<VideoView>(Resource.Id.UserVid);
video.Holder.AddCallback((this));