技术背景

好多开发者,希望我们能够分享下如何实现Unity下的camera场景采集并推送rtmp服务,然后低延迟播放出来。简单来说,在Unity 中实现采集 Camera 场景并推送RTMP的话,先是获取 Camera 场景数据,通过创建 RenderTexture 和读取图像数据到 Texture2D。选择选择合适的RTMP推送库或SDK,并设置推流地址和初始化推流。然后说明了推送数据时需要将图像数据转换为合适格式并推送到服务器,如果需要推送音频,还可以采集unity场景的audio或麦克风、扬声器audio数据,在结束推流时要停止推流并释放资源。

技术实现

本文以大牛直播SDK的Windows平台Unity下camera场景采集,并推送RTMP服务为例,先说

创建 RenderTexture:在 Unity 中,使用 RenderTexture 类来创建一个用于捕获 Camera 图像的纹理。

Texture2D image_texture = textures_poll_.get(video_width_, video_height_);
if (null == image_texture)
   return;

RenderTexture old_camera_rt = camera_.targetTexture;
camera_.targetTexture = render_texture_;
camera_.Render();

RenderTexture old_rt = RenderTexture.active;

RenderTexture.active = render_texture_;

image_texture.ReadPixels(new Rect(0, 0, video_width_, video_height_), 0, 0, false);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

构建FrameTexture:

/* SmartPublisherWinMono.cs
 * Created by daniusdk.com on 2018/05/10.
 */
public class FrameTexture
{
          
          
	public FrameTexture(Texture2D texture, IntPtr video_buffer, int video_buffer_size,
		int video_width, int video_height, int is_vertical_flip, int is_horizontal_flip, int scale_width, int scale_height, bool is_alpha)
	{
          
          
		texture_ = texture;
		video_buffer_ = video_buffer;
		video_buffer_size_ = video_buffer_size;
		video_width_ = video_width;
		video_height_ = video_height;
		is_vertical_flip_ = is_vertical_flip;
		is_horizontal_flip_ = is_horizontal_flip;
		scale_width_ = scale_width;
		scale_height_ = scale_height;
		is_alpha_ = is_alpha;
	}

	public Texture2D texture_;
	public IntPtr video_buffer_;
	public int video_buffer_size_;
	public int video_width_;
	public int video_height_;
	public int is_vertical_flip_;
	public int is_horizontal_flip_;
	public int scale_width_;
	public int scale_height_;
	public bool is_alpha_;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.

拿到数据后,通过SendImage()发送数据的大牛直播SDK封装后的RTMP推送模块。

private bool sendImage()
{
          
          
	FrameTexture frame;
	if (frames_.TryDequeue(out frame))