如何录制音频或视频 (HTML)

[ 本文适用于编写 Windows 运行时应用的 Windows 8.x 和 Windows Phone 8.x 开发人员。如果你要针对 Windows 10 进行开发,请参阅 最新文档 ]

你可从相机录制视频和/或从麦克风录制音频。

说明

初始化 MediaCaptureSettings

MediaCaptureSettings 属性为 MediaCapture 对象提供配置设置。使用 MediaCaptureInitializationSettings 类初始化这些属性,如下面的示例中所示。

// Initialize the MediaCaptureInitialzationSettings.
function initCaptureSettings() {
    captureInitSettings = null;
    captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
    captureInitSettings.audioDeviceId = "";
    captureInitSettings.videoDeviceId = "";
    captureInitSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audioAndVideo;
    captureInitSettings.photoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.videoPreview;
    if (deviceList.length > 0)
        captureInitSettings.videoDeviceId = deviceList[0].id;
}

创建 MediaCapture 对象

MediaCapture 对象包含捕获视频需要的方法和异步操作。

    oMediaCapture = new Windows.Media.Capture.MediaCapture();

初始化 MediaCapture 对象

使用 MediaCapture.InitializeAsync 方法可以初始化 MediaCapture 对象。默认情况下,InitializeAsync 使用默认的视频捕获设备并且将捕获音频或视频。或者,你可以创建并初始化自己的 MediaCaptureInitializationSettings 对象并将它传递到 InitializeAsync 方法。

// Create and initialze the MediaCapture object.
function initMediaCapture() {
    oMediaCapture = null;
    oMediaCapture = new Windows.Media.Capture.MediaCapture();
    oMediaCapture.initializeAsync(captureInitSettings).then (function (result) {
       createProfile();
    }, errorHandler);    
}

创建编码配置文件

编码配置文件中包含有关如何对目标文件进行编码的所有设置。Windows.Media.MediaProperties API 提供了几个用于创建 MediaEncodingProfile 对象的选项。

Windows.Media.MediaProperties 命名空间提供了一组预定义的编码配置文件:

  • AAC 音频 (M4A)
  • MP3 音频
  • Windows Media 音频 (WMA)
  • MP4 视频(H.264 视频加 AAC 音频)
  • Windows Media 视频 (WMV)

此列表中的前三个配置文件仅包含音频,另外两个既包含视频又包含音频。

以下代码为 MP4 视频创建配置文件。

// Create a profile.
function createProfile() {
    profile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp4(
        Windows.Media.MediaProperties.VideoEncodingQuality.hd720p);
}

静态 CreateMp4 方法创建 MP4 编码配置文件。此方法的参数为视频提供目标分辨率。在这种情况下,VideoEncodingQuality.HD720p 表示在每秒 30 帧情况下的 1280 x 720 像素。("720p" 表示每帧 720 逐行扫描行)。用来创建预定义配置文件的其他方法均遵循此模式。

或者,你可以通过使用 Windows.Media.MediaProperties.MediaEncodingProfile.CreateFromFileAsync 方法来创建与现有媒体文件相匹配的配置文件。或者,如果你知道所需的确切编码设置,则可以创建一个新的 Windows.Media.MediaProperties.MediaEncodingProfile 对象并填充所有的配置文件详细信息。

开始录制

要开始将视频捕获到文件中,请为捕获到的视频创建一个文件。然后调用 StartRecordToStorageFileAsync 方法,并传入 MediaEncodingProfile 和目标存储文件中。

// Start the video capture.
function startMediaCaptureSession() {
   Windows.Storage.KnownFolders.videosLibrary.createFileAsync("cameraCapture.mp4", Windows.Storage.CreationCollisionOption.generateUniqueName).then(function (newFile) {
        storageFile = newFile;
        oMediaCapture.startRecordToStorageFileAsync(profile, storageFile).then(function (result) {           
           
        }, errorHandler);
    }  );   
}

停止录制

要停止捕获视频,请调用 StopRecordAsync 方法。

// Stop the video capture.
function stopMediaCaptureSession() {
    oMediaCapture.stopRecordAsync().then(function (result) {
        
    }, errorHandler);         
}

完整示例

以下示例显示了录制视频到文件的步骤如何汇集到一起。


var oMediaCapture;
var profile;
var captureInitSettings;
var deviceList = new Array();
var recordState = false;
var storageFile;



function errorHandler(e) {
    sdkSample.displayStatus(e.message + ", Error Code: " + e.code.toString(16));
}



// Begin initialization.
function initialization() {
    document.getElementById("message").innerHTML = "Initialization started.";
    enumerateCameras();   
}


// Identify available cameras.
function enumerateCameras() {
    var deviceInfo = Windows.Devices.Enumeration.DeviceInformation;
    deviceInfo.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).then(function (devices) {
        // Add the devices to deviceList
        if (devices.length > 0) {
           
            for (var i = 0; i < devices.length; i++) {
                deviceList.push(devices[i]);              
            }
     
            initCaptureSettings();
            initMediaCapture();
            document.getElementById("message").innerHTML = "Initialization complete.";

        } else {
            sdkSample.displayError("No camera device is found ");            
        }
    }, errorHandler);
}


// Initialize the MediaCaptureInitialzationSettings.
function initCaptureSettings() {
    captureInitSettings = null;
    captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
    captureInitSettings.audioDeviceId = "";
    captureInitSettings.videoDeviceId = "";
    captureInitSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audioAndVideo;
    captureInitSettings.photoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.videoPreview;
    if (deviceList.length > 0)
        captureInitSettings.videoDeviceId = deviceList[0].id;
}


// Create a profile.
function createProfile() {
    profile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp4(
        Windows.Media.MediaProperties.VideoEncodingQuality.hd720p);
}

// Create and initialze the MediaCapture object.
function initMediaCapture() {
    oMediaCapture = null;
    oMediaCapture = new Windows.Media.Capture.MediaCapture();
    oMediaCapture.initializeAsync(captureInitSettings).then (function (result) {
       createProfile();
    }, errorHandler);    
}


// Start the video capture.
function startMediaCaptureSession() {
   Windows.Storage.KnownFolders.videosLibrary.createFileAsync("cameraCapture.mp4", Windows.Storage.CreationCollisionOption.generateUniqueName).then(function (newFile) {
        storageFile = newFile;
        oMediaCapture.startRecordToStorageFileAsync(profile, storageFile).then(function (result) {           
           
        }, errorHandler);
    }  );   
}

// Stop the video capture.
function stopMediaCaptureSession() {
    oMediaCapture.stopRecordAsync().then(function (result) {
        
    }, errorHandler);         
}

适当清理 MediaCapture 资源

警告  

当应用暂停时,你需要正确关机并处理 MediaCapture 对象和相关对象,这一点十分重要。如果此操作失败,则可能会干扰访问设备相机的其他应用,从而给你的应用用户体验带来负面影响。

在 Windows Phone 上,在 oncheckpoint 应用生命周期事件的处理程序中清理 MediaCapture 资源。在 Windows 上,使用 SoundLevelChanged 事件并检查音量是否已静音。如果已静音,则清理 MediaCapture 资源。如果事件指示任何其他音量,请使用该事件重新创建它们。请注意,即使你在应用运行时手动静音/取消静音,此事件也不会触发你的代码。因此,此事件有效地实现了与手机上的暂停和恢复相同的作用。这是必需的,因为在 Windows 上,用户可能能够在应用之间进行切换,而无需暂停当前应用。

 

你应该在 Windows Phone 的 oncheckpoint 事件或 Windows 的 SoundLevelChanged 中清理媒体捕获资源,如指南上面的说明所述。执行此操作的一个好方法是声明一些变量以存储 MediaCapture 对象和可指示该应用当前正在录制还是预览视频的布尔值。然后,创建一个用于停止录制或预览(如果它们正在进行中)、调用 MediaCapture 对象的结束方法并将其设置为 Null 的函数。以下代码显示了实现此方法的示例。

function cleanupCaptureResources()
{
    var promises = [];

    if (mediaCapture) {
        if (isRecording) {
            promises.push(mediaCapture.stopRecordAsync().then(function () {
                isRecording = false;
            }));
        }

        promises.push(new WinJS.Promise(function (complete) {
            mediaCapture.close();
            mediaCapture = null;
            complete();
        }));
    }

    return WinJS.Promise.join(promises).done(null, errorHandler);
}

最后,将以下代码添加到 oncheckpoint 事件处理程序中。使用承诺调用你的清理方法非常重要。这可确保系统在暂停你的应用之前完成该方法。

app.oncheckpoint = function (args) {
    args.setPromise(
        cleanupCaptureResources()
    );
};

相关主题

媒体捕获示例