tencent cloud

Mobile Live Video Broadcasting

Quick Start (Flutter)

다운로드
포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-11-18 11:33:45
This guide walks you through building a basic live streaming app with host broadcasting and audience viewing using the core AtomicLiveWidget from the AtomicXCore SDK, along with AtomicPusher (for host streaming) and AtomicPlayer (for audience playback).

Key Features

AtomicLiveWidget is a lightweight widget designed specifically for live streaming, serving as the canvas for your video layout. On the host side, AtomicPusher handles local audio/video capture and streaming. On the audience side, AtomicPlayer manages stream playback. Both sides use setView to render video onto the same AtomicLiveWidget. You only need to focus on building your UI and interaction logic.
The diagram below shows where AtomicLiveWidget fits into your live streaming interface:


Preparation

Step 1: Activate Service

See Activate the Service to obtain either a trial or paid version of the SDK.

Step 2: Import AtomicXCore

1. Install the package: Add the atomic_x_core dependency to your pubspec.yaml, then run flutter pub get.
dependencies:
atomic_x_core: ^5.3.0
2. Configure permissions: Both Android and iOS projects require permission setup.
Android
iOS
Add camera and microphone permissions to your android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Add camera and microphone permissions to your app’s Podfile in the iOS directory and Info.plist in the ios/Runner directory.
Podfile
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
'PERMISSION_MICROPHONE=1',
'PERMISSION_CAMERA=1',
]
end
end
end
Info.plist
<key>NSCameraUsageDescription</key>
<string>TUILiveKit needs access to your camera. Video recording will have visuals only after enabling this permission.</string>
<key>NSMicrophoneUsageDescription</key>
<string>TUILiveKit needs access to your microphone. Video recording will have audio only after enabling this permission.</string>


Step 3: Implement Login

Call LoginStore.shared.login in your project to complete login. This is required before using any AtomicXCore features.
Important:
Only call LoginStore.shared.login after your app's user account login succeeds, to ensure clear and consistent login logic.
import 'package:flutter/material.dart';
import 'package:atomic_x_core/atomicxcore.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();

final result = await LoginStore.shared.login(
sdkAppID: 1400000001, // Replace with your sdkAppID
userID: "test_001", // Replace with your userID
userSig: "xxxxxxxxxxx", // Replace with your userSig
);

if (result.isSuccess) {
debugPrint("login success");
} else {
debugPrint("login failed code: ${result.errorCode}, message: ${result.errorMessage}");
}

runApp(const MyApp());
}
Login API Parameter Description:
Parameter
Type
Description
sdkAppId
int
The ID of the live application created in the Console.
userId
string
Unique identifier for the current user. Use only letters, numbers, hyphens, and underscores. Avoid simple IDs like 1, 123, etc., to prevent multi-device login conflicts.
userSig
string
A ticket for Tencent Cloud authentication. Please note:
Development Environment: You can use the local GenerateTestUserSig.genTestSig function to generate a UserSig or generate a temporary UserSig via the UserSig Generation Tool.
Production Environment: To prevent key leakage, you must use a server-side method to generate UserSig. For details, see Generating UserSig on the Server.

Building a Basic Live Room

Step 1: Implement Host Broadcasting

Host broadcasting involves three steps: create the streaming view, enable the camera and microphone, and call startPush to go live. AtomicLiveWidget continuously renders both the local preview and the streaming video—there’s no need to switch between preview and live views.



1. Core Logic and State Definition
Define the rendering view, controller, and AtomicPusher in your State class. Add a _isLiveStarted flag to control the visibility of the "Go Live" button.
class _YourAnchorPageState extends State<YourAnchorPage> {
// Core components
late final AtomicLiveController _controller;
late final AtomicLiveWidget _videoView;
final AtomicPusher _pusher = AtomicPusher.shared;
// State flag: false = preview; true = live
bool _isLiveStarted = false;

@override
void initState() {
super.initState();
_controller = AtomicLiveController.create(AtomicLiveViewType.pushView);
_videoView = AtomicLiveWidget(controller: _controller);
// Bind rendering view; after binding, you see the local preview
_pusher.setView(_videoView);

// Enable devices on initialization (see next step)
_openDevices();
}
}
2. Enable Camera and Microphone
Call DeviceStore.shared.openLocalCamera and DeviceStore.shared.openLocalMicrophone to enable the camera and microphone. AtomicLiveWidget will automatically preview the camera stream, no extra steps needed.
Note:
This step is required for preview. AtomicLiveWidget only renders video after devices are enabled.
void _openDevices() {
// 1. Open front camera (true = front)
DeviceStore.shared.openLocalCamera(true);
// 2. Enable microphone
DeviceStore.shared.openLocalMicrophone();
}
3. Build Preview View
Place AtomicLiveWidget in your page. Preview and live share the same view, no need to switch components.
// 3.1 Wrap rendering view component
Widget _buildVideoView() {
return Container(
color: Colors.black,
child: _videoView,
);
}

// 3.2 Compose main view
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
// View layer: preview and live share AtomicLiveWidget
Positioned.fill(
child: _buildVideoView(),
),
// UI layer: Go Live button (only visible during preview)
if (!_isLiveStarted)
Positioned(
bottom: 50, left: 0, right: 0,
child: Center(
child: ElevatedButton(
onPressed: _startLive, // Implement this method in the next step
child: const Text('Go Live'),
),
),
),
],
),
);
}
4. Start and End Live
Call AtomicPusher.startPush to start streaming.
Future<void> _startLive() async {
// 1. Configure live room parameters
final config = PusherInfo(
liveID: widget.liveId, // Unique room identifier
liveName: "Atomic Live Demo", // Room title
);

// 2. Start streaming
_pusher.startPush(config);
debugPrint("Live started successfully");

// 3. Update state to hide Go Live button
setState(() {
_isLiveStarted = true;
});
}
PusherInfo Parameter Details
Parameter Name
Type|
Attribute
Description
liveID
String
Required
Unique identifier for the live room.
liveName
String
Optional
Title of the live room.
notice
String
Optional
Announcement for the live room.
metaData
Map
Optional
Custom metadata for the live room.
isPublicVisible
Boolean
Optional
Whether the room is publicly visible (true: yes, false: no).
coverURL
String
Optional
Cover image URL for the live room.
backgroundURL
String
Optional
Cover image URL for the live room.
categoryList
List
Optional
Background image URL for the live room.
5. End Live
After the live ends, call AtomicPusher.stopPush to stop streaming. The SDK will handle stopping the stream and destroying the room.
Future<void> _stopLive() async {
// End live
_pusher.stopPush();
debugPrint("Live ended successfully");

// Exit current page
if (mounted) {
Navigator.of(context).pop();
}
}
6. Complete Code Example
For quick integration, combine the above steps into a complete YourAnchorPage file. You can copy the following code:
import 'package:flutter/material.dart';
import 'package:atomic_x_core/atomicxcore.dart';

class YourAnchorPage extends StatefulWidget {
final String liveId;
const YourAnchorPage({super.key, required this.liveId});

@override
State<YourAnchorPage> createState() => _YourAnchorPageState();
}

class _YourAnchorPageState extends State<YourAnchorPage> {
late final AtomicLiveController _controller;
late final AtomicLiveWidget _videoView;
final AtomicPusher _pusher = AtomicPusher.shared;
bool _isLiveStarted = false; // Live status flag

@override
void initState() {
super.initState();
_controller = AtomicLiveController.create(AtomicLiveViewType.pushView);
_videoView = AtomicLiveWidget(controller: _controller);
_pusher.setView(_videoView); // Bind rendering view
_openDevices(); // Enable devices
}

void _openDevices() {
DeviceStore.shared.openLocalCamera(true);
DeviceStore.shared.openLocalMicrophone();
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
// View layer: preview and live share AtomicLiveWidget
Positioned.fill(
child: Container(
color: Colors.black,
child: _videoView,
),
),
// Go Live button
if (!_isLiveStarted)
Positioned(
bottom: 50, left: 0, right: 0,
child: Center(
child: ElevatedButton(onPressed: _startLive, child: const Text('Go Live')),
),
),
],
),
);
}

// Go Live logic
void _startLive() {
final config = PusherInfo(
liveID: widget.liveId,
liveName: "Test Live",
);
_pusher.startPush(config);
setState(() {
_isLiveStarted = true; // Switch UI state
});
}
}

Step 2: Implement Audience Viewing

Enable audience viewing with a few simple steps.



1. Build Audience Playback Page
In your audience page, create an AtomicLiveWidget and use AtomicLiveController and AtomicPlayer to control playback.
Note:
Always call setView to bind AtomicLiveWidget to AtomicPlayer before calling joinChannel().
Technical Details: AtomicPlayer binds to the rendering view via setView, independent of widget mounting. You can call setView before the widget mounts; the binding completes automatically when the view is ready. After joinChannel succeeds, call startPlay to begin playback, or the screen will remain black.
import 'package:flutter/material.dart';
import 'package:atomic_x_core/atomicxcore.dart';

/// YourAudiencePage represents your audience viewing page
class _YourAudiencePageState extends State<YourAudiencePage> {
late final AtomicLiveController _controller;
late final AtomicLiveWidget _videoView;
final AtomicPlayer _player = AtomicPlayer();
bool _isJoining = true;

@override
void initState() {
super.initState();
_controller = AtomicLiveController.create(AtomicLiveViewType.playView);
_videoView = AtomicLiveWidget(controller: _controller);
// Bind rendering view
_player.setView(_videoView);

// Enter the live room after the first frame is rendered to ensure AtomicLiveWidget is initialized
WidgetsBinding.instance.addPostFrameCallback((_) {
_joinLive();
});
}

Future<void> _joinLive() async {
final result = await _player.joinChannel(widget.liveId);
if (result.isSuccess) {
debugPrint("joinChannel success");
// Playback URL is generated from liveId using livekit://liveid=<liveId>
_player.startPlay("livekit://liveid=${widget.liveId}");
if (mounted) setState(() => _isJoining = false);
} else {
debugPrint("joinChannel error: ${result.errorMessage}");
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
// Always render; do not remove based on _isJoining, or video will be interrupted
_videoView,

if (_isJoining)
const Center(child: CircularProgressIndicator(color: Colors.white)),
],
),
);
}
}
2. Join Live Room and Watch
Call AtomicPlayer.setView to bind the rendering view, then call joinChannel to join the live room. After joining, call startPlay to play the current room's stream.
import 'package:flutter/material.dart';
import 'package:atomic_x_core/atomicxcore.dart';

/// YourAudiencePage represents your audience viewing page
class YourAudiencePage extends StatefulWidget {
final String liveId;

const YourAudiencePage({super.key, required this.liveId});

@override
State<YourAudiencePage> createState() => _YourAudiencePageState();
}

class _YourAudiencePageState extends State<YourAudiencePage> {
late final AtomicLiveController _controller;
late final AtomicLiveWidget _videoView;
final AtomicPlayer _player = AtomicPlayer();

@override
void initState() {
super.initState();
_controller = AtomicLiveController.create(AtomicLiveViewType.playView);
_videoView = AtomicLiveWidget(controller: _controller);
// Bind rendering view
_player.setView(_videoView);
// Join live room
_joinLive();
}

Future<void> _joinLive() async {
// Call joinChannel to enter the live room; after success, call startPlay to begin playback
// - liveId: same liveId as host broadcasting
final result = await _player.joinChannel(widget.liveId);

if (result.isSuccess) {
debugPrint("joinChannel success");
_player.startPlay("livekit://liveid=${widget.liveId}");
} else {
debugPrint("joinChannel error: ${result.errorMessage}");
// If join fails, also exit the page
// if (mounted) Navigator.of(context).pop();
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
_videoView,
],
),
);
}
}
3. Exit Live
When the audience leaves the live room, call AtomicPlayer.stopPlay and leaveChannel to exit. The SDK will automatically stop playback and exit the room.
import 'package:flutter/material.dart';
import 'package:atomic_x_core/atomicxcore.dart';

/// YourAudiencePage represents your audience viewing page
class YourAudiencePage extends StatefulWidget {
final String liveId;

const YourAudiencePage({super.key, required this.liveId});

@override
State<YourAudiencePage> createState() => _YourAudiencePageState();
}

class _YourAudiencePageState extends State<YourAudiencePage> {
// ... other code ...

// Exit live
Future<void> _leaveLive() async {
_player.stopPlay();
_player.leaveChannel();

debugPrint("leaveLive success");
}

// ... other code ...
}

Step 3: Listen for Live Events

After the audience joins the live room, handle "passive" events such as the host ending the live or the audience being kicked out. If you don't listen for these events, the audience UI may stay on a black screen, affecting user experience.
Use PlayerListener to listen for events.
import 'package:flutter/material.dart';
import 'package:atomic_x_core/atomicxcore.dart';

/// YourAudiencePage represents your audience viewing page
class YourAudiencePage extends StatefulWidget {
final String liveId;

const YourAudiencePage({super.key, required this.liveId});

@override
State<YourAudiencePage> createState() => _YourAudiencePageState();
}

class _YourAudiencePageState extends State<YourAudiencePage> {
late final AtomicLiveController _controller;
late final AtomicLiveWidget _videoView;
final AtomicPlayer _player = AtomicPlayer();
// 1. Define PlayerListener to manage event listening
late final PlayerListener _playerListener;

@override
void initState() {
super.initState();
_controller = AtomicLiveController.create(AtomicLiveViewType.playView);
_videoView = AtomicLiveWidget(controller: _controller);
_player.setView(_videoView);
// 2. Listen for live events
_setupLiveEventListener();
// 3. Join live room
_joinLive();
}

// 4. Set up event listener
void _setupLiveEventListener() {
_playerListener = PlayerListener(
liveEnded: (reason) {
// Listen for live end event
debugPrint("Live ended. reason: ${reason.name}");
// Handle exit logic here, e.g., close the current page
// if (mounted) Navigator.of(context).pop();
},
kickedOut: (reason, message) {
// Listen for being kicked out of live
debugPrint("Kicked out of live. reason: ${reason.name}, message: $message");
// Handle exit logic here
// if (mounted) Navigator.of(context).pop();
},
);
_player.addListener(_playerListener);
}

Future<void> _joinLive() async {
final result = await _player.joinChannel(widget.liveId);
if (result.isSuccess) {
debugPrint("joinChannel success");
_player.startPlay("livekit://liveid=${widget.liveId}");
} else {
debugPrint("joinChannel error: ${result.errorMessage}");
}
}

Future<void> _leaveLive() async {
_player.stopPlay();
_player.leaveChannel();
debugPrint("leaveLive success");
}

@override
void dispose() {
// 5. Remove event listener
_player.removeListener(_playerListener);
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
_videoView,
],
),
);
}
}

Live Streaming Layouts

After integrating AtomicLiveWidget, you have a clean video rendering view. The host streams via AtomicPusher, the audience plays via AtomicPlayer, and all video is rendered onto this widget. The widget itself does not include any interactive UI. To enhance your live streaming experience, see Enrich Live Streaming Scenarios.
Layout Type
Dynamic Grid Layout
Floating Window Layout
Fixed Grid Layout
Fixed Window Layout
Template ID
600
601
800
801
Description
Default layout, dynamically adjusts grid size based on the number of co-hosts.
Co-host guests are displayed in floating windows.
Fixed number of co-hosts, each guest occupies a fixed grid.
Fixed number of co-hosts, guests are displayed in fixed windows.
Live Streaming Results













Enrich Live Streaming Scenarios

After you’ve built the basic live streaming functionality, refer to the following guides to add interactive features to your live stream.
Live Feature
Feature Description
Feature Stores
Implementation Guide
Audience Audio/Video Co-hosting
Audience can request to take a mic seat and interact with the host via real-time video.
Host Cross-room Co-hosting PK
Hosts from different rooms can connect for interaction or PK.
Add Live Comments Chat
Audience can send and receive real-time text messages in the live room.
Build Gift System
Audience can send virtual gifts to the host, increasing interaction and fun.

API Documentation

Store/Component
Feature Description
API Documentation
AtomicPusher
Host streaming: local audio/video capture and preview, start/stop streaming, live room info updates, streaming status/statistics, event callbacks.
AtomicPlayer
Audience playback: rendering view binding, join/leave channel, start/stop playback, playback status/statistics, event callbacks.
LiveListStore
Live room lifecycle management: create/join/leave/destroy room, query room list, modify live info (name, announcement, etc.), listen for live status (e.g., kicked out, ended).
DeviceStore
Audio/video device control: microphone (on/off/volume), camera (on/off/switch/quality), screen sharing, real-time device status monitoring.
CoGuestStore
Audience co-host management: co-host requests/invitations/accept/reject, co-host member permissions (microphone/camera), status sync.
CoHostStore
Host cross-room co-hosting: supports multiple layout templates (dynamic grid, etc.), initiate/accept/reject co-hosting, co-host interaction management.
BattleStore
Host PK battle: initiate PK (set duration/opponent), manage PK status (start/end), sync scores, listen for battle results.
GiftStore
Gift interaction: get gift list, send/receive gifts, listen for gift events (including sender, gift details).
BarrageStore
Live comments: send text/custom comments, maintain comment list, real-time comment status monitoring.
LikeStore
Like interaction: send likes, listen for like events, sync total like count.
LiveAudienceStore
Audience management: get real-time audience list (ID/name/avatar), count audience number, listen for audience join/leave events.
AudioEffectStore
Audio effects: voice change (child/male), reverb (KTV, etc.), monitor adjustment, switch effects in real time.
BaseBeautyStore
Basic beauty: adjust smoothing/whitening/rosiness (0-100 levels), reset beauty state, sync effect parameters.

FAQs

Why is the screen black with no video after the host calls startPush or the audience calls joinChannel?

Check setView: Make sure you called setView to bind AtomicLiveWidget to AtomicPusher or AtomicPlayer before calling the go live or watch API.
Check device permissions: Confirm the app has system permissions for camera and microphone.
Check host side: Did the host call DeviceStore.shared.openLocalCamera(true) to enable the camera?
Check network: Verify the device's network connection.

Audience called joinChannel and returned Success, but still no video?

Playback timing: Did you call startPlay after joinChannel succeeded? See above for calling startPlay after joining the room.
Controller type: Did you use AtomicLiveViewType.playView when creating the controller?
Widget persistence: Was AtomicLiveWidget accidentally destroyed or recreated due to setState during room join? Ensure it remains stable in the widget tree.

How to request permissions in a Flutter project?

Use the permission_handler plugin to request camera and microphone permissions:
import 'package:permission_handler/permission_handler.dart';

Future<void> requestPermissions() async {
await [
Permission.camera,
Permission.microphone,
].request();
}

How to handle page lifecycle in Flutter?

Clean up resources in the dispose method, such as removing event listeners:
@override
void dispose() {
_player.removeListener(_playerListener);
super.dispose();
}


도움말 및 지원

문제 해결에 도움이 되었나요?

피드백