Esta página ainda não está disponível no idioma selecionado. Estamos trabalhando para adicionar mais opções de idiomas. Agradecemos sua compreensão.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
On this page

Show all

SDK Usage

Updated on 2023-11-14 GMT+08:00
  1. Check whether a browser is compatible with the SDK. For details, see checkSystemRequirements.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
      async isBrowserSupport() {
        let check = false
        try {
          check = await HRTC.checkSystemRequirements()
          console.warn('browser isSupport: ' + check)
        } catch (error) {
          console.error(`check browser isSupport error: ${error.getCode()} - ${error.getMsg()}`)
          if (error.getCode() !== 90100025) {
            console.error(`browser Support part ability of RTC`)
            check = true
          }
        }
        return check
     }
    

  2. Create a client. For details, see createClient.

    1
    2
    let config = { appId,domain,countryCode }
    let client = HRTC.createClient(config)
    
    • domain: domain name of the server. The type is string[128]. This parameter is mandatory in SDK 1.0+ and optional in SDK 2.0+.
    • appId: (mandatory) The type is string[128]. Only apps with the same app ID can access the same room.
    • countryCode: (optional) The type is string[2]. For example, CN indicates the Chinese mainland, US indicates the United States, and HK indicates Hong Kong (China). For details about countryCode values, see GRS Country Codes.
    NOTE:

    For details about how to obtain the values of domain and appId, submit a service ticket.

  3. Join a room. For details, see join.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    let option = { userId: userId, userName: userName, signature: signature, ctime: ctime, role: role } 
    async joinRoom() {
       try{
         await client.join(roomId, option)
         console.log('join room success')
       } catch(error){
         console.log('join room fail',error)
       }
    }
    
    • userId: (mandatory) unique ID of a local user. The type is string[64].
    • userName: (optional) user nickname encoded in UTF-8 format. The type is string[256].
    • signature: (mandatory) authentication signature. You need to obtain it from the remote server. The type is string[512].
      NOTE:

      You need to deploy the remote server. For details, see Access Authentication.

    • ctime: (mandatory) UTC timestamp in seconds. The type is string.
    • role: (mandatory) user role, which can be used to identify the media direction. The type is number. The options are as follows:
      • 0: joiner (publish and watch media).
      • 2: player (watch but not publish media).
    • roomId: (mandatory) room ID. The type is string[64].

    When the user joins the room, the peer client will receive the peer-join event.

  4. Create and publish a local stream. For details, see createStream, initialize, addResolution, publish, and play.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    let stream = HRTC.createStream({ audio:true,microphoneId:xxx,video:true,cameraId:xxx })
    
    
    stream.initialize().then(() => {
      stream.addResolution('90p_1')  // Optional. If you enable dual streams, you can add a video of another resolution.
      
      stream.play(elementId,{muted:true})   // Play the local stream.
      client.publish(stream)
    })
    
    • audio: (optional) whether to collect audio from microphones. The type is Boolean. The default value is false.
    • video: (optional) whether to collect video from cameras. The type is Boolean. The default value is false.
    • microphoneId: (optional) ID of the microphone for audio collection. This parameter is valid only when audio is set to true. The type is string. If this parameter is not passed, the system automatically uses the default value.
    • cameraId: (optional) ID of the camera for video collection. This parameter is valid only when video is set to true. The type is string. If this parameter is not passed, the system automatically uses the default value.

  5. When receiving the stream-added event notification from the server, subscribe to the remote media. For details, see stream-added, subscribe, and getStreamInfo.

    1
    2
    3
    4
    client.on('stream-added', (event) => {
      const stream = event.stream
      client.subscribe(stream,{ video:true, audio:true })
    })
    
    NOTE:
    1
    2
    3
    4
    5
    6
    7
    Dual-stream scenario:
    client.on('stream-added', (event) => {
      const stream = event.stream
      const streamInfo = stream.getStreamInfo()  // Obtain information such as the stream resolution.
      const resolutionIds = streamInfo.videoProfiles.map((profile) => profile.resolutionId) // The app selects the resolution based on the service scenario.
      client.subscribe(stream,{video:true, audio:true, resolutionIds:resolutionIds})  // Subscribe to audio and video of the selected resolution.
    })
    

    When the subscription is complete, the local client will receive the stream-subscribed event notification. Set a peer screen to play the audio and video of the peer client. For details, see stream-subscribed and play.

    1
    2
    3
    4
    client.on('stream-subscribed', (event) => {
       const stream = event.stream
       stream.play(elementId, { objectFit: 'contain', muted: true, resolutionId: resolutionId })
    })
    
    • elementId: ID of an HTML <div> tag.
    • Play parameters:
      • objectFit: (optional) The type is string. The value can be contain, cover, or fill. Default value: cover for video; contain for presentation.
      • muted: (optional) The type is Boolean. true indicates muted; false indicates unmuted. The default value is false.
      • resolutionId: (optional) resolution of the video to be played. The type is string. By default, the video with the highest resolution is played.

    If the user does not need to view the video of the peer client, unsubscribe from the audio and video of the peer client. For details, see unsubscribe.

    1
    client.unsubscribe(stream)
    

  6. When the remote client leaves the room, the local client will receive the peer-leave event. You can clear the resources of the remote client. For details, see peer-leave.

    1
    2
    3
    client.on('peer-leave', (event) => {
       // just do something...
    })
    

    event.userId: peer user ID, which is obtained by listening to the peer-leave event.

    When the remote client leaves the room, the local client will receive the stream-removed event notification. You can close the video screen in the event processing function. For details, see stream-removed.

    1
    2
    3
    client.on('stream-removed', (event) => {
       event.stream.close()
    })
    

    The close function is called using the stream object. This function will remove the video tag element created using play and disable the camera and microphone.

  7. Leave the room. For details, see leave.

    1
    client.leave()
    

    Call this API to leave the room when the voice or video call ends.

    The process of a general voice and video call is completed.

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback