Talk to us
Talk to us
menu

How to Use the Mini-game in Live Streaming

How to Use the Mini-game in Live Streaming

In today’s vibrant entertainment industry, businesses face fierce competition in capturing and retaining audience attention. User retention and engagement have become pivotal objectives for companies striving to establish a lasting presence. To address this challenge, an increasing number of businesses are integrating mini-games into social platforms, a strategic move validated by industry leaders.

This fusion of mini-games with social media not only enhances user interaction but also fosters a sense of community among audiences. It represents a bridge between entertainment and engagement, offering a captivating and immersive experience that transcends traditional boundaries. This innovative approach not only retains existing users but also attracts new audiences to interactive and engaging content, positioning it as a strategic beacon in navigating the evolving digital entertainment landscape.

In this guide, we will introduce different gameplays of mini-game and walk through how to implement the mini-game in live streaming.

Host play game with fans

The host can invite the audience who have sent more gifts to play highly interactive games together. This can encourage the audience to send more gifts, increase the stickiness between the host and high-value audience, provide topics and increase interactivity in the live-streaming room, and enhance the viewing experience of the audience.

Recommend games: Ludo, UMO, Knife Challenge, Bumper Blaster

Implementing the host playing games with audience function

As shown in the figure, the following steps are required for the host to invite the audience to play games together:

  1. The host selects a game and requests the business server interface.
  2. After receiving the request, the business server needs to call the Send in-room messages interface to notify the room members to load the game.
  3. Room members obtain the game loading information by listening to the onReceiveRoomMessage callback and loading the game.
  4. After the host has loaded the game, they invite the audience to play the game by calling the sendMessage interface.
  5. When the audience receives the invitation, they can choose to accept or reject it. If the audience agrees, they can join the game by calling the joinGame interface.

The audience plays betting games

Adding simple and exciting lucky or betting games during live streaming, attract fans to participate in interactive activities, enhance the atmosphere of the live streaming, and increases engagement through a rich bonus pool and exciting gameplay.

Simultaneously displaying the rewards won by the audience in the live streaming can attract more users to participate in the game. By using game bets and the rewards won by the audience, the host can receive more gifts after the audience wins their rewards.

Recommend games: 777, Crazy Racing

Implement the audience play betting game

As shown in the figure, the live streaming room will start a game after a certain waiting time (such as 30 seconds). The audience can join the game at any time and place bets during the waiting time.

  1. The audience selects the game they want to play and calls the loadGame and joinGame interfaces to load and join the game.
  2. If it is during the waiting time for the game, audiences can choose to place bets. If the game has already started, viewers need to wait for the next round to place bets.
  3. After the countdown timer ends, the game will start automatically.
  4. After the game ends, the business server will select the users who have won a large amount of gold coins and broadcast this in live streaming to encourage more users to join the game.

Implement Live Streaming Kit + Mini Game

Integrate Live Streaming Kit

Live Streaming Kit is a feature-rich livestream component, which enables you to build custom live streaming into your apps with only a few lines of code. And you can also customize various live streaming features by configuring parameters. You can integrate the Live Streaming Kit SDK according to the official documentation.

Integrate Mini-Game SDK

Import Mini-Game SDK

iOS

Add the SudMGPWrapper_Lite SDK import to the ios/Podfile file.

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  pod 'SudMGPWrapper_Lite',

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

Then open the Terminal application, navigate to the ios directory, and run the pod install command to install the Mini-Game SDK.

Android

Download the latest version of the SDK from GitHub and copy the AAR file to the android/app/libs directory. Also, add a reference to the SDK in the android/app/build.gradle file.

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.squareup.okhttp3:okhttp:4.9.1'
    
    implementation files('libs/SudMGP-v1.3.0.1120-lite.aar')
}

Import Game Plugin

iOS
  1. Copy the following files to the ios/Runner directory.
SudMGPPlugin.h
SudMGPPlugin.m
QueueUtils.h
QueueUtils.m
  1. Add plugin registration in the AppDelegate.
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
      SudMGPPlugin.register(with: registrar(forPlugin: "SudMGPPlugin")!)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
Android
  1. Add the SudMGPPlugin file to the android/app/src/main/kotlin/com/zegocloud/uikit/flutter/live_streaming directory.
  2. Register SudMGPPlugin in the MainActivity file.
class MainActivity: FlutterActivity() {
    @SuppressLint("LongLogTag")
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        try {
            flutterEngine.plugins.add(SudMGPPlugin())
        } catch (e: Exception) {
            Log.e(
                "GeneratedPluginRegistrant",
                "Error registering plugin SudMGPPlugin, com.zegocloud.minigame.demo.SudMGPPlugin",
                e
            )
        }
    }
}
Flutter
  1. Add the game_plugin.dart file to the lib directory.
  2. Call the registerEventHandler method in the live_page.dart file.
  void initState() {
    super.initState();
    liveController = ZegoUIKitPrebuiltLiveStreamingController();
    SudMGPPlugin.registerEventHandler(onGameEvent);
  }

Implement Mini Game Background Authentication Logic

The ZEGOCLOUD Mini Game SDK uses a background authentication service, so it is necessary to implement the authentication interface in the background according to the development documentation.

Add Mini Game Entry

Add the getCode, initGameSDK, and loadGame interfaces in live_page.dart. The detailed implementation logic is as follows:

class LivePage extends StatefulWidget {
  final String liveID;
  final bool isHost;

  const LivePage({
    Key? key,
    required this.liveID,
    this.isHost = false,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => LivePageState();
}

class LivePageState extends State<LivePage> {
  ZegoUIKitPrebuiltLiveStreamingController? liveController;

  String _authcode = '';
  Widget? _gameView;
  final GlobalKey _gameViewKey = GlobalKey();
  final widgetsBinding = WidgetsFlutterBinding.ensureInitialized();


  @override
  void initState() {
    super.initState();
    liveController = ZegoUIKitPrebuiltLiveStreamingController();
    SudMGPPlugin.registerEventHandler(onGameEvent);
    getCode();
    initGameSDK();
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      loadGame();
    });
  }

  @override
  void dispose() {
    super.dispose();
    liveController = null;
  }

  void getCode() {
    getRequest(MG_NAME_LOGIN_AUTH_URL, '/api/get_code', {
      'uid': localUserID
    }).then((rsp) => setState(() {
      if (rsp['ret_code'] == 0) {
        _authcode = rsp['data']['code'];
      }
    }));
  }

  void initGameSDK() {
    SudMGPPlugin.initSDK(MG_APPID, MG_APPKEY, MG_APP_IS_TEST_ENV);
  }

  void loadGame() {
    if (TargetPlatform.android ==
        defaultTargetPlatform) {
      loadAndroidGame();
    } else if (TargetPlatform.iOS ==
        defaultTargetPlatform) {
      loadIOSGame();
    }
  }

  void loadIOSGame() {
    _gameView = getPlatformView('SudMGPPluginView', (int viewid)
    {
      print("Start Load Game");
      SudMGPPlugin.loadGame(
          localUserID,
          widget.liveID,
          _authcode,
          1468180338417074177,
          "default",
          getGameViewSize(),
          getGameConfig())
          .then((ret) {
        setState(() => {});
      });
    });
  }

  void loadAndroidGame() {
    SudMGPPlugin.loadGame(
        localUserID,
        widget.liveID,
        _authcode,
        1468180338417074177,
        "default",
        getGameViewSize(),
        getGameConfig())
        .then((ret) { setState(() => _gameView = getPlatformView(
          'SudMGPPluginView',
              (int viewid) => {}));
        });
  }

  void onGameEvent(Map map) {
    String method = map['method'];
    switch (method) {
      case 'onGameStarted':
        setState(() {
        });
        break;
      case 'onGameDestroyed':
        break;
      case 'onGameStateChange':
        break;
      case 'onGetGameCfg':
        break;
      case 'onPlayerStateChange':
        break;
      case 'onExpireCode':
        break;
      default:
    }
  }

  String getGameViewSize() {
    final screenWidth = MediaQuery.of(context).size.width * widgetsBinding.window.devicePixelRatio;
    final screenHeight = MediaQuery.of(context).size.height * widgetsBinding.window.devicePixelRatio * 0.5;

    return json.encode({
      "view_size": {"width": screenWidth, "height": screenHeight},
      "view_game_rect": {"left": 0, "top": 0, "right": 0, "bottom": 0}
    });
  }

  String getGameConfig() {
    return json.encode({});
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: ZegoUIKitPrebuiltLiveStreaming(
        appID: Your app ID /*input your AppID*/,
        appSign: 'Your app Sign' /*input your AppSign*/,
        userID: localUserID,
        userName: 'user_$localUserID',
        liveID: widget.liveID,
        controller: liveController,
        config: (widget.isHost
            ? ZegoUIKitPrebuiltLiveStreamingConfig.host()
            : ZegoUIKitPrebuiltLiveStreamingConfig.audience())
          ..avatarBuilder = customAvatarBuilder
        ..foreground = Positioned(bottom:10, right:10, child: ElevatedButton(
          child: Text('Play Game'),
          onPressed: () {
            loadGame();
            showModalBottomSheet(
              context: context,
              builder: (BuildContext context) {
                return Container(
                  height: MediaQuery.of(context).size.height,
                  child: Center(
                    child: _gameView,
                  ),
                );
              },
            ).whenComplete(() {

            });
          },
        )),
      ),
    );
  }
}


Ready to start building with ZEGOCLOUD’s sdk? Click here to get 10,000 minutes for free.

Let’s Build APP Together

Start building with real-time video, voice & chat SDK for apps today!

Talk to us

Take your apps to the next level with our voice, video and chat APIs

Free Trial
  • 10,000 minutes for free
  • 4,000+ corporate clients
  • 3 Billion daily call minutes

Stay updated with us by signing up for our newsletter!

Don't miss out on important news and updates from ZEGOCLOUD!

* You may unsubscribe at any time using the unsubscribe link in the digest email. See our privacy policy for more information.