This topic describes the features and usage of the Push software development kit (SDK) for Android. It covers the main SDK interfaces, the basic workflow, and provides examples for related features to help developers understand and use the SDK for live stream ingest.
Features
Supports stream ingest over Real-Time Messaging Protocol (RTMP).
Supports RTS stream ingest and pulling based on Real-Time Communication (RTC).
Supports co-streaming and battles.
Adopts H.264 for video encoding and AAC for audio encoding.
Supports custom configurations for features such as bitrate control, resolution, and display mode.
Supports various camera operations.
Supports real-time retouching and custom retouching effects.
Allows you to add and remove animated stickers as watermarks.
Allows you to stream screen recordings.
Supports external audio and video inputs in different formats such as YUV and pulse-code modulation (PCM).
Supports mixing of multiple streams.
Supports ingest of audio-only and video-only streams and stream ingest in the background.
Supports background music.
Supports video snapshot capture.
Supports automatic reconnection and error handling.
Supports Automatic Gain Control (AGC), Automatic Noise Reduction (ANR), and Acoustic Echo Cancellation (AEC) algorithms.
Allows you to switch between the software and hardware encoding modes for video files. This improves the stability of the encoding module.
Limitations
Take note of the following limits before you use Push SDK for Android:
You must configure screen orientation before stream ingest. You cannot rotate the screen during live streaming.
You must disable auto screen rotation for stream ingest in landscape mode.
In hardware encoding mode, the value of the output resolution must be a multiple of 16 to be compatible with the encoder. For example, if you set the resolution to 540p, the output resolution is 544 × 960. You must scale the screen size of the player based on the output resolution to prevent black bars.
API references
Procedure
The basic procedure is as follows:
Feature usage
Register the SDK
For information about how to apply for and configure a license, see Integrate a license for the Push SDK.
You must register the SDK before you can use its stream ingest features.
Call the license registration method early in your application's lifecycle, before you use the Push SDK.
AlivcLiveBase.setListener(new AlivcLiveBaseListener() {
@Override
public void onLicenceCheck(AlivcLivePushConstants.AlivcLiveLicenseCheckResultCode result, String reason) {
Log.e(TAG, "onLicenceCheck: " + result + ", " + reason);
}
});
AlivcLiveBase.registerSDK();The AlivcLiveBase class lets you set log levels, specify local log paths, and retrieve the SDK version.
Call the registerSDK method in AlivcLiveBase to register the SDK license.
In the onLicenceCheck method of the AlivcLiveBase#setListener interface, you can asynchronously check if the license is configured.
NoteThis callback is triggered only after the pusher instance is initialized.
Configure stream ingest parameters
Basic stream ingest parameters have default values, which we recommend using. This allows for a simple initialization with no extra configuration.
// Initialize the stream ingest configuration class.
AlivcLivePushConfig mAlivcLivePushConfig = new AlivcLivePushConfig();
// Set the stream ingest mode. The default is the basic stream ingest mode.
mAlivcLivePushConfig.setLivePushMode(AlivcLiveMode.AlivcLiveBasicMode);
// Set the resolution. The default is 540p.
mAlivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_540P);
// Set the frame rate. The default is 20 fps.
mAlivcLivePushConfig.setFps(AlivcFpsEnum.FPS_25);
// Set the video encoding Group of Pictures (GOP). Unit: seconds. The default is 2 seconds.
mAlivcLivePushConfig.setVideoEncodeGop(AlivcVideoEncodeGopEnum.GOP_TWO);
// Enable bitrate control. This is enabled by default.
mAlivcLivePushConfig.setEnableBitrateControl(true);
// Set the screen orientation. The default is portrait. You can set the device to landscape with the home button on the left or right.
mAlivcLivePushConfig.setPreviewOrientation(AlivcPreviewOrientationEnum.ORIENTATION_PORTRAIT);
// Set the audio encoding mode. The default is AAC-LC.
mAlivcLivePushConfig.setAudioProfile(AlivcAudioAACProfileEnum.AAC_LC);
// Set the video encoding mode. The default is hardware encoding.
mAlivcLivePushConfig.setVideoEncodeMode(AlivcEncodeModeEnum.Encode_MODE_HARD);
// Set the audio encoding mode. The default is software encoding.
mAlivcLivePushConfig.setAudioEncodeMode(AlivcEncodeModeEnum.Encode_MODE_SOFT);
// Set the camera type. The default is the front camera.
mAlivcLivePushConfig.setCameraType(AlivcLivePushCameraTypeEnum.CAMERA_TYPE_FRONT);
// Set the image to ingest when the app runs in the background or is paused.
mAlivcLivePushConfig.setPausePushImage("TODO: Image Path");
// Set the image to ingest in poor network conditions.
mAlivcLivePushConfig.setNetworkPoorPushImage("TODO: Image Path");For optimal performance on mobile devices and to manage network bandwidth, we recommend setting the resolution to 540p. Most mainstream live streaming applications use this resolution.
If you disable bitrate control, the bitrate is fixed at the initial bitrate. It does not automatically adjust between the target and minimum bitrates. If network conditions are unstable, this may cause playback stuttering. Use this option with caution.
Ingest a camera stream
Initialize the SDK.
After you configure the stream ingest parameters, use the init method of the Push SDK to initialize it. The following sample code shows how to do this:
AlivcLivePusher mAlivcLivePusher = new AlivcLivePusher(); mAlivcLivePusher.init(mContext, mAlivcLivePushConfig);NoteAlivcLivePusher does not support multiple instances. Each init call must have a corresponding destroy call.
Register preview callbacks.
You can register preview callbacks using the setLivePushInfoListener method:
/** * Set stream ingest notification events. * * @param infoListener The notification listener. */ mAlivcLivePusher.setLivePushInfoListener(new AlivcLivePushInfoListener() { @Override public void onPreviewStarted(AlivcLivePusher pusher) { // A notification that the preview has started. } // Other Override methods //.... //.... });Start the preview.
After the livePusher object is initialized and the callbacks are configured, you can start the preview. You must pass the SurfaceView for the Camera preview. The following sample code shows how to do this:
mAlivcLivePusher.startPreview(mSurfaceView)// Start the preview. You can also call the asynchronous startPreviewAysnc method as needed.Start stream ingest.
Add the following code inside the onPreviewStarted callback method.
mAlivcLivePusher.startPush(mPushUrl);NoteIngest URLs support RTMP and Real-Time Streaming (RTS) (artc://). For information about how to obtain an ingest URL, see Generate ingest and streaming URLs.
ApsaraVideo Live does not support ingesting multiple streams to the same ingest URL at the same time. The second stream ingest request is rejected.
Common stream ingest methods
Stream ingest controls include starting, stopping, restarting, pausing, and resuming the stream, along with stopping the preview and destroying the stream ingest instance. You can add buttons to perform these operations based on your application's requirements.
/* You can call this method to pause an active stream. After you pause stream ingest, the video preview and video stream ingest remain on the last frame, and the audio stream continues. */
mAlivcLivePusher.pause();
/* You can call this method to resume a paused stream. After you resume stream ingest, the audio and video previews and stream ingest return to normal. */
mAlivcLivePusher.resume();
/* You can call this method to stop an active stream. After the operation is complete, stream ingest stops. */
mAlivcLivePusher.stopPush();
/* You can call this method to stop the preview only when the preview is active. Calling this method on an active stream has no effect. After the preview stops, the preview image freezes on the last frame. */
mAlivcLivePusher.stopPreview();
/* You can call this method to restart stream ingest when the stream is active or when you receive any Error-related callbacks. In an Error state, you can only call this method, reconnectPushAsync to reconnect, or destroy to destroy the stream ingest. After the operation is complete, stream ingest restarts. All resources within ALivcLivePusher, including the preview and stream ingest, are restarted. */
mAlivcLivePusher.restartPush();
/* You can call this method when the stream is active or when you receive an Error callback related to AlivcLivePusherNetworkDelegate. In an Error state, you can only call this method, restartPush to restart stream ingest, or destroy to destroy the stream ingest. After the operation is complete, the stream ingest reconnects to the RTMP URL. */
mAlivcLivePusher.reconnectPushAsync();
/* After the stream ingest is destroyed, stream ingest and the preview stop, and the preview image is removed. All resources related to AlivcLivePusher are destroyed. */
mAlivcLivePusher.destroy();Camera-related operations
Camera-related operations are available during stream ingest, pause, and reconnection. You can switch cameras and manage settings for the flash, focus, zoom, and image. The following sample code shows how to do this:
/* Switch between the front and rear cameras. */
mAlivcLivePusher.switchCamera();
/* Turn the flash on or off. You cannot turn on the flash when using the front camera. */
mAlivcLivePusher.setFlash(true);
/* Adjust the focus to zoom the captured image. The zoom range is [0, getMaxZoom()]. */
mAlivcLivePusher.setZoom(5);
/* Manually focus. Manual focus requires two parameters: 1. point: The coordinates of the point to focus on. 2. autoFocus: Specifies whether to enable autofocus. This parameter is effective only for the current focus operation. Subsequent autofocus behavior follows the setting of the autofocus interface mentioned above. */
mAlivcLivePusher.focusCameraAtAdjustedPoint(x, y, true);
/* Set whether to enable autofocus. */
mAlivcLivePusher.setAutoFocus(true);
/* Set the image. There are two image-related interfaces: PushMirror for the ingest stream image and PreviewMirror for the preview image. The PushMirror setting affects only the playback image. The PreviewMirror setting affects only the preview image. The two do not affect each other. */
mAlivcLivePusher.setPreviewMirror(false);
mAlivcLivePusher.setPushMirror(false);You can call camera-related interfaces only after the preview starts.
Ingest a screen sharing stream
The Push SDK supports ingesting screen sharing streams. Before you configure screen sharing, you must initialize the SDK, set up the preview, and start the stream ingest. Screen recording uses MediaProjection, which requires you to request user permission. To enable screen recording mode, pass the data returned from the permission request through this interface. By default, the camera is not enabled during screen recording.
Set up screen sharing stream ingest
// resultData: The system intent for screen recording.
mAlivcLivePushConfig.setMediaProjectionPermissionResultData(resultData);Set the screen rotation
In screen recording mode, you can set the screen rotation angle to support both landscape and portrait recording. The following sample code shows how to do this:
mAlivcLivePusher.setScreenOrientation(0);You must listen for OrientationEventListener events at the application layer. When the screen orientation changes, pass the new rotation angle to this interface.
Set privacy protection
When a streamer needs to perform sensitive operations, such as entering a password during screen recording, they can enable the privacy protection feature. After the operation is complete, the streamer can disable privacy protection. The following sample code shows how to do this:
mAlivcLivePusher.pauseScreenCapture();// Enable privacy protection.
mAlivcLivePusher.resumeScreenCapture();// Disable privacy protection.If you pause screen recording and have set setPausePushImage in the configuration, viewers see an image after this interface is called. If not, viewers see the last frame.
Ingest both screen sharing and camera streams
When ingesting a screen sharing stream, you can enable the camera to ingest both screen sharing and camera streams. There are two scenarios for ingesting both screen sharing and camera streams:
The streamer has a camera preview.
Both the streamer and viewers can see the camera feed.
The streamer does not have a camera preview.
For example, during a game live stream, the streamer does not want the camera view to block the game screen. However, the live content that viewers see includes the streamer's camera feed.
The streamer has a camera preview
After screen recording is successfully enabled, call the interface to enable or disable the camera preview.
mAlivcLivePusher.startCamera(surfaceView);// Enable the camera preview.
mAlivcLivePusher.stopCamera();// Disable the camera preview.In screen recording mode, we recommend that you set the width and height of the camera preview surfaceView to a 1:1 ratio. This way, you do not need to adjust the surfaceView when the screen rotates.
If the width and height are not set to a 1:1 ratio, you must adjust the surfaceView's ratio when the screen rotates, then call stopCamera and then startCamera.
If the streamer does not need a preview, set surfaceView to null.
The streamer does not have a camera preview
When the streamer does not need a camera preview but the viewers do, you can enable camera stream mixing.
mAlivcLivePusher.startCameraMix(x, y, w, h);// Enable camera stream mixing and set the mixing layout with x, y, w, and h.
mAlivcLivePusher.stopCameraMix();// Stop camera stream mixing.Preview display modes
The Push SDK supports three preview modes. The preview display mode does not affect stream ingest.
ALIVC_LIVE_PUSHER_PREVIEW_SCALE_FILL: The preview fills the window. If the video and window aspect ratios are different, the preview is distorted.
ALIVC_LIVE_PUSHER_PREVIEW_ASPECT_FIT: The preview maintains the video's aspect ratio. If the video and window aspect ratios are different, black bars appear in the preview.
ALIVC_LIVE_PUSHER_PREVIEW_ASPECT_FILL: The preview is cropped to fit the window's aspect ratio. If the video and window aspect ratios are different, parts of the video are cropped.
The following sample code shows how to set the preview mode:
mAlivcLivePushConfig.setPreviewDisplayMode(AlivcPreviewDisplayMode.ALIVC_LIVE_PUSHER_PREVIEW_ASPECT_FIT);Image stream ingest
To improve the user experience, the Push SDK lets you ingest a static image when the application is in the background or when the bitrate is too low.
When the application is moved to the background, video stream ingest is paused by default, and only the audio stream is ingested. During this time, you can ingest a static image. For example, you can display an image that says, "Streamer is away for a moment and will be back soon".
mAlivcLivePushConfig.setPausePushImage("Path to the background PNG image");// Set the image for background stream ingest.When the network is poor, you can configure the SDK to ingest a static image. After you set the image, the SDK automatically ingests it when a low bitrate is detected, which helps avoid video stream stuttering. The following sample code shows how to do this:
mAlivcLivePushConfig.setNetworkPoorPushImage("Path to the poor network PNG image");// Set the image to ingest when the network is poor.Ingest an audio-only stream
mAlivcLivePushConfig.setAudioOnly(true);Ingest external audio and video streams
The Push SDK supports ingesting audio and video from external sources, such as an audio or video file.
Before you can ingest external audio and video streams, you must enable the custom audio and video stream input feature.
/**
* Other parameters, such as output resolution, audio sampling rate, and number of channels, are set in the config file using setResolution, setAudioSampleRate, and setAudioChannels.
*/
mAlivcLivePushConfig.setExternMainStream(true,AlivcImageFormat.IMAGE_FORMAT_YUVNV12,AlivcSoundFormat.SOUND_FORMAT_S16);After you enable the custom audio and video stream input feature, you can ingest external audio and video streams.
Ingest an external audio stream
/**
* This interface does not control the timing. The caller needs to control the timing of the input audio frames.
*/
mAlivcLivePusher.inputStreamAudioData(byte[] data, int size, int sampleRate, int channels, long pts);Ingest an external video stream
/**
* This interface does not control the timing. The caller needs to control the timing of the input video frames.
*/
mAlivcLivePusher.inputStreamVideoData(byte[] data, int width, int height, int stride, int size, long pts, int rotation);Configure watermarks
The Push SDK provides a feature for adding watermarks and supports multiple watermarks on a single stream. The watermark image must be a PNG file. The following sample code shows how to add a watermark:
mAlivcLivePushConfig.addWaterMark(waterPath,0.1,0.2,0.3);// Add a watermark.The x, y, and width parameters are relative values. For example, x=0.1 means the x-coordinate of the watermark is at 10% of the x-axis of the ingest screen. If the ingest resolution is 540 × 960, the x-coordinate of the watermark is 54.
The height of the watermark image is scaled proportionally to the input width value based on the actual width and height of the watermark image.
To implement a text watermark, first convert the text to an image, and then use this interface to add the watermark.
Set the video quality
Three video quality modes are supported: Resolution Priority, Fluency Priority, and Custom.
To set the video quality, you must enable bitrate control: mAlivcLivePushConfig.setEnableBitrateControl(true);
Resolution Priority (default)
In Resolution Priority mode, the SDK internally configures the bitrate parameters to prioritize the definition of the ingested video.
mAlivcLivePushConfig.setQualityMode(AlivcQualityModeEnum.QM_RESOLUTION_FIRST);// Resolution priorityFluency Priority
In Fluency Priority mode, the SDK internally configures the bitrate parameters to prioritize the fluency of the ingested video.
mAlivcLivePushConfig.setQualityMode(AlivcQualityModeEnum.QM_FLUENCY_FIRST);// Fluency priorityCustom mode
In Custom mode, the SDK configures the bitrate based on the developer's settings. When you set the mode to Custom, you must define the initial, minimum, and target bitrates.
Target bitrate: When the network is good, the bitrate gradually increases to the target bitrate to improve video definition.
Minimum bitrate: When the network is poor, the bitrate gradually decreases to the minimum bitrate to reduce video stuttering.
Initial bitrate: The bitrate at the start of the live stream.
mAlivcLivePushConfig.setQualityMode(AlivcQualityModeEnum.QM_CUSTOM);// Custom mode
mAlivcLivePushConfig.setTargetVideoBitrate(1000); // Target bitrate: 1,000 kbps
mAlivcLivePushConfig.setMinVideoBitrate(300); // Minimum bitrate: 300 kbps
mAlivcLivePushConfig.setInitialVideoBitrate(800); // Initial bitrate: 800 kbpsWhen you set a custom bitrate, refer to the recommended settings from Alibaba Cloud to configure the bitrates. For more information, see the following tables:
Table 1. Recommended settings for Resolution Priority mode
Resolution | initialVideoBitrate | minVideoBitrate | targetVideoBitrate |
360p | 600 | 300 | 1000 |
480p | 800 | 300 | 1200 |
540p | 1000 | 600 | 1400 |
720p | 1500 | 600 | 2000 |
1080p | 1800 | 1200 | 2500 |
Table 1. Recommended settings for Resolution Priority mode
Resolution | initialVideoBitrate | minVideoBitrate | targetVideoBitrate |
360p | 400 | 200 | 600 |
480p | 600 | 300 | 800 |
540p | 800 | 300 | 1000 |
720p | 1000 | 300 | 1200 |
1080p | 1500 | 1200 | 2200 |
Adaptive resolution
Adaptive resolution dynamically adjusts the ingest resolution. When this feature is enabled, the resolution is automatically lowered in poor network conditions to improve video fluency and definition. The following sample code shows how to enable this feature:
mAlivcLivePushConfig.setEnableAutoResolution(true); // Enable adaptive resolution. It is disabled by default.Adaptive resolution takes effect only when the video quality mode is set to Resolution Priority or Fluency Priority. It is not effective in Custom mode.
Some players may not support dynamic resolution. To use the adaptive resolution feature, we recommend that you use ApsaraVideo Player.
Background music
The Push SDK provides features for background music, including playback, mixing, denoising, in-ear monitoring, and muting. The following sample code shows how to use these features:
/* Start playing background music. */
mAlivcLivePusher.startBGMAsync(mPath);
/* Stop playing background music. If background music is playing and you need to switch songs, simply call the start background music interface. You do not need to stop the currently playing background music. */
mAlivcLivePusher.stopBGMAsync();
/* Pause background music. You can call this interface only after the background music starts playing. */
mAlivcLivePusher.pauseBGM();
/* Resume background music. You can call this interface only when the background music is paused. */
mAlivcLivePusher.resumeBGM();
/* Enable loop playback for music. */
mAlivcLivePusher.setBGMLoop(true);
/* Set the denoise switch. After you turn on denoising, non-human voice parts of the captured sound are filtered. This may slightly suppress the human voice. We recommend that you let users choose whether to enable the denoising feature. It is not used by default. */
mAlivcLivePusher.setAudioDenoise(true);
/* Set the in-ear monitoring switch. The in-ear monitoring feature is mainly used in KTV scenarios. After you turn on in-ear monitoring, the streamer can hear their own voice in the headphones. After you turn it off, the streamer cannot hear their voice in the headphones. In-ear monitoring does not work without headphones. */
mAlivcLivePusher.setBGMEarsBack(true);
/* Set mixing to adjust the volume of the background music and captured human voice. */
mAlivcLivePusher.setBGMVolume(50);// Set the background music volume.
mAlivcLivePusher.setCaptureVolume(50);// Set the captured human voice volume.
/* Set mute. After you mute, both the music and human voice input are muted. To mute only the music or human voice, use the mixing volume setting interface. */
mAlivcLivePusher.setMute(true);You can call background music-related interfaces only after the preview starts.
Capture snapshots during stream ingest
The Push SDK provides a feature to capture snapshots of the local video stream. The following sample code shows how to do this:
// Capture a snapshot of the video stream. Parameters: number of images to capture, interval between each image, and interface callback.
pusher.snapshot(1, 1, new AlivcSnapshotListener() {
@Override
public void onSnapshot(Bitmap bmp) {
// You can dump the snapshot to a local PNG file. The following is sample code:
String dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SS").format(new Date());
File f = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "snapshot-" + dateFormat + ".png");
if (f.exists()) {
f.delete();
}
try {
FileOutputStream out = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});Background running and screen locking
When the app is moved to the background or the screen is locked, you can call the pause() or resume() method of AlivcLivePusher to pause or resume stream ingest.
For non-system audio and video calls, the SDK captures and ingests the sound. You can call the mAlivcLivePusher.setMute(true or false) interface when the application is moved to the background or the screen is locked to control whether audio is captured in the background, based on your application's requirements.
Callback listeners
Callback type | Callback class name | Set method |
AlivcLivePushInfoListener |
| |
AlivcLivePushNetworkListener |
| |
AlivcLivePushErrorListener |
| |
AlivcLivePushBGMListener |
|
Stream ingest callbacks
Stream ingest callbacks notify your application of the SDK's status, including when the preview starts, the first video frame is rendered, the first audio or video frame is sent, stream ingest starts, and stream ingest stops.
onPushStarted: indicates that the connection to the server is successful.
onFirstFramePushed: indicates that the first audio or video frame was sent successfully.
onPushStarted and onFirstFramePushed: indicate that the SDK stream ingest was successful.
Network-related callbacks
Network-related callbacks notify your application of the SDK's network and connection status. The SDK automatically attempts to reconnect during short network fluctuations or network transitions that are within the reconnection timeout and retry count set in AlivcLivePushConfig. If the reconnection is successful, stream ingest continues.
onConnectFail: Indicates that stream ingest failed. This can happen if the ingest URL is invalid, contains invalid characters, has authentication issues, exceeds the maximum concurrent stream ingest limit, or is on the stream ingest blacklist. Before you try to ingest the stream again, make sure the ingest URL is valid and available. The specific error codes are 0x30020901 to 0x30020905 and 0x30010900 to 0x30010901.
onConnectionLost: A callback for a disconnected link. After the link is disconnected, the SDK automatically starts the reconnection process and triggers onReconnectStart. If the stream ingest link is not restored after the maximum number of retries (config.connectRetryCount), the SDK triggers onReconnectFail.
onNetworkPoor: A callback for a slow network. When you receive this callback, it means the current network is not sufficient to support the stream ingest. At this point, stream ingest is still ongoing and has not been interrupted. You can handle your business logic here, such as displaying a UI notification to the user.
onNetworkRecovery: A callback for network recovery.
onReconnectFail: This method is called when the network disconnection duration exceeds the reconnection timeout and retry count set in AlivcLivePushConfig, causing the SDK's automatic reconnection to fail. After the network recovers, you can call the
mAlivcLivePusher.reconnectPushAsyncinterface to reconnect.onSendDataTimeout: A callback for a data sending timeout. You should check the current network status. When the network recovers, stop the current stream ingest and then restart it.
onPushURLAuthenticationOverdue: A callback for an expired authentication. This callback indicates that the authentication for the current ingest URL has expired. You must provide a new URL to the SDK.
Error callbacks
onSystemError: A callback for a system device exception. You must destroy the engine and try again.
onSDKError: An SDK error callback. You must handle it differently based on the error code:
If the error code is 805438211, it indicates poor device performance and a low encoding and rendering frame rate. You should notify the streamer and stop time-consuming business logic at the application layer, such as advanced retouching and animations.
You must handle callbacks for when the application does not have microphone or camera permissions. The error code for no microphone permission is 268455940, and the error code for no camera permission is 268455939.
For all other errors, log them for troubleshooting and do not perform any other operations.
Background music callbacks
onOpenFailed: Failed to start the background music. Check if the music path and file passed to the start background music interface are correct. You can call startBGMAsync to try playing it again.
onDownloadTimeout: Background music playback timed out. This often occurs when playing background music from a network URL. You should prompt the streamer to check the current network status. You can call startBGMAsync to try playing it again.
Common methods and interfaces
Common methods
/* In Custom mode, users can adjust the minimum and target bitrates in real time. */
mAlivcLivePusher.setTargetVideoBitrate(800);
mAlivcLivePusher.setMinVideoBitrate(400);
/* Check if autofocus is supported. */
mAlivcLivePusher.isCameraSupportAutoFocus();
/* Check if the flash is supported. */
mAlivcLivePusher.isCameraSupportFlash();
/* Get the status of whether stream ingest is in progress. */
mAlivcLivePusher.isPushing();
/* Get the ingest URL. */
mAlivcLivePusher.getPushUrl();
/* Get the stream ingest performance debugging information. For specific parameters and descriptions of stream ingest performance, see the API documentation or interface comments. */
mAlivcLivePusher.getLivePushStatsInfo();
/* Get the version number. */
mAlivcLivePusher.getSDKVersion();
/* Set the log level to filter the desired debugging information as needed. */
mAlivcLivePusher.setLogLevel(AlivcLivePushLogLevelAll);
/* Get the current SDK status. */
mAlivcLivePusher.getCurrentStatus();
/* Get the last error code. If there is no error, it returns ALIVC_COMMON_RETURN_SUCCESS. */
mAlivcLivePusher.getLastError();List of common interfaces
Class | Description |
AlivcLivePushConfig | Initial stream ingest configuration |
AlivcLivePusher | Stream ingest feature class |
AlivcLivePusherErrorListener | Error callback |
AlivcLivePusherNetworkListener | Network-related notification callback |
AlivcLivePusherInfoListener | Stream ingest-related information callback |
AlivcLivePusherBGMListener | Background music callback |
AlivcLivePushCustomFilter | Custom filter callback |
AlivcLivePushCustomDetect | Custom face detection callback |
AlivcSnapshotListener | Snapshot callback |
Integrate the retouching feature
To use the retouching feature in the Push SDK, you must import the retouching library and configure the corresponding callbacks.
To use the retouching feature, you must obtain a license for the Queen SDK. For instructions, see Obtain a license for the Queen SDK.
Import the retouching library and retouching panel using Maven. Add the following code to the build.gradle file of your project. For the latest version of the Queen SDK, see the latest Demo:
implementation "com.aliyun.maliang.android:queen:2.5.0-official-full" implementation("com.aliyun.maliang.android:queen_menu:2.5.0-official-full") { exclude group: 'com.aliyun.maliang.android', module: 'queen' }You can also integrate the LiveBeauty module from the Demo:
File or folder
Feature description
live_beauty
Basic abstract class for retouching
queen_beauty
Basic UI control for retouching
Get the LiveBeauty plugin library.
Use the
clonecommand to download the plugin library code from this path (LiveBeauty) to your local machine.git clone https://github.com/MediaBox-Demos/amdemos-android-live.gitOpen the command line in the root directory of your Android Studio project. Run the following code, and then use
File > New > Import Moduleto import theLiveBeautymodule into your Android project.git submodule add https://github.com/MediaBox-Demos/amdemos-android-live.git ***/***/***NoteIn the sample code, "***/***/***" represents the location where you want to place the
LiveBeautymodule.In the project's
settings.gradlefile, add the module's path:include ':app', ':LiveBeauty', ':LiveBeauty:live_queenbeauty'NoteIn the sample code, "app" represents the main module.
In the main module's
build.gradlefile, add a dependency on theLiveBeautymodule:dependencies { implementation project(':LiveBeauty') implementation project(':LiveBeauty:live_queenbeauty') }Click
File > Sync Project with Gradle Files. Wait for Gradle to sync. Then, you can use theLiveBeautymodule.
Configure the retouching plugin UI module.
In your project's layout XML file, add the
QueenBeautyMenucontrol. For example:<com.aliyunsdk.queen.menu.QueenBeautyMenu android:id="@+id/beauty_beauty_menuPanel" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" />In the Activity, initialize
QueenBeautyMenu. For example:// Initialize the retouching menu panel. QueenMenuPanel beautyMenuPanel = QueenBeautyMenu.getPanel(context); beautyMenuPanel.onHideMenu(); beautyMenuPanel.onHideValidFeatures(); beautyMenuPanel.onHideCopyright(); // Add the retouching menu to the layout. QueenBeautyMenu beautyBeautyContainerView = findViewById(R.id.beauty_beauty_menuPanel); beautyBeautyContainerView.addView(beautyMenuPanel);
Set the face detection and retouching callbacks.
To integrate a third-party retouching library, you can set the setCustomDetect and setCustomFilter callbacks.
The data parameter returned in the customDetectProcess (long data, int width, int height, int rotation, int format, long extra) callback function of AlivcLivePushCustomDetect is a pointer to the captured data. A third-party retouching library can recognize or process the data from this pointer.
The inputTexture parameter returned in the customFilterProcess (int inputTexture, int textureWidth, int textureHeight, long extra) callback function of AlivcLivePushCustomFilter is the texture of the image. A third-party retouching library can process this texture. To return a processed texture, return its texture ID. Otherwise, return the original inputTexture.
Usage notes
Note the following when you use the Push SDK for Android:
Item | Description |
Obfuscation rules | Check the obfuscation rules. Make sure that the SDK-related package names are added to the list of packages that are not obfuscated. |
Method calls |
|
FAQ
Stream ingest fails
You can use the self-service troubleshooting tool to check if the ingest URL is valid.
How do I obtain information about ingested streams?
You can go to Stream Management to view and manage ingested audio and video streams on the Active Streams tab.
How do I play a stream?
After you start stream ingest, you can use a player, such as ApsaraVideo Player, FFplay, or VLC, to test stream pulling. For information about how to obtain a playback URL, see Generate ingest and streaming URLs.