day123:MoFang:直播間列表資訊的前後端實現&創建房間的前後端實現

目錄

1.服務端提供所有直播間的列表資訊

2.前端顯示房間列表

3.創建房間

1.服務端提供所有直播間的列表資訊

1.marshmallow.py

from marshmallow_sqlalchemy import SQLAlchemyAutoSchema,auto_field
from .models import LiveStream,db
from application.apps.users.models import User
from marshmallow import post_dump
class StreamInfoSchema(SQLAlchemyAutoSchema):
    id = auto_field()
    name = auto_field()
    room_name = auto_field()
    user = auto_field()

    class Meta:
        model = LiveStream
        include_fk = True
        include_relationships = True
        fields = ["id","name","room_name","user"]
        sql_session = db.session

    @post_dump()
    def user_format(self, data, **kwargs):
        user = User.query.get(data["user"])
        if user is None:
            return data

        data["user"] = {
            "id":user.id,
            "nickname": user.nickname if user.nickname else "",
            "ip": user.ip_address if user.ip_address else "",
            "avatar": user.avatar if user.avatar else ""
        }
        return data

marshmallow.py

2.views.py

from .marshmallow import StreamInfoSchema
from flask import current_app
@jsonrpc.method("Live.stream.list")
@jwt_required # 驗證jwt
def list_stream():
    # 驗證登陸用戶資訊
    current_user_id = get_jwt_identity() # get_jwt_identity 用於獲取載荷中的數據
    user = User.query.get(current_user_id)
    if user is None:
        return {
            "errno": status.CODE_NO_USER,
            "errmsg": message.user_not_exists,
            "data": {

            }
        }

    # 查詢資料庫中所有的直播流
    stream_list = LiveStream.query.filter(LiveStream.status==True, LiveStream.is_deleted==False).all()
    sis = StreamInfoSchema()
    data_list = sis.dump(stream_list,many=True)

    # 使用requests發送get請求,讀取當前srs中所有的直播流和客戶端列表
    import requests,re,json
    stream_response = requests.get(current_app.config["SRS_HTTP_API"]+"streams/")
    client_response = requests.get(current_app.config["SRS_HTTP_API"]+"clients/")
    stream_text = re.sub(r'[^\{\}\/\,0-9a-zA-Z\"\'\:\[\]\._]', "", stream_response.text)
    client_text = re.sub(r'[^\{\}\/\,0-9a-zA-Z\"\:\[\]\._]', "", client_response.text)
    stream_dict = json.loads(stream_text)
    client_dict = json.loads(client_text)
    
    # 在循環中匹配所有的客戶端對應的總人數和當前推流用戶的IP地址
    for data in data_list:
        data["status"] = False
        for stream in stream_dict["streams"]:
            if data["name"] == stream["name"]:
                data["status"] = stream["publish"]["active"]
                break
        data["clients_number"] = 0
        for client in client_dict["clients"]:
            if data["name"] == client["url"].split("/")[-1]:
                data["clients_number"]+=1
            if client["publish"] and "/live/"+data["name"]==client["url"]:
                data["user"]["ip"] = client["ip"]
    return {
        "errno": status.CODE_OK,
        "errmsg": message.ok,
        "stream_list": data_list
    }

views.py

2.前端顯示房間列表

1.房間列表頁面初始化:live_list.html

把上面的客戶端live_list.html,修改成live.html,並新建live_list.html,程式碼:

<!DOCTYPE html>
<html>
<head>
    <title>好友列表</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta charset="utf-8">
    <link rel="stylesheet" href="../static/css/main.css">
    <script src="../static/js/vue.js"></script>
    <script src="../static/js/axios.js"></script>
    <script src="../static/js/main.js"></script>
    <script src="../static/js/uuid.js"></script>
    <script src="../static/js/settings.js"></script>
</head>
<body>
    <div class="app setting" id="app">
        <div class="bg">
      <img src="../static/images/rooms_bg.png">
    </div>
        <img class="back" @click="goto_home" src="../static/images/user_back.png" alt="">
        <div class="add_friend_btn" @click="add_room">
            <img src="../static/images/add_room.png" alt="">
        </div>
    <div class="friends_list room_list">
            <div class="item" v-for="room in rooms">
                <div class="avatar">
                    <img class="user_avatar" :src="room.avatar" alt="">
                </div>
                <div class="info">
                    <p class="username">{{room.name}}</p>
                    <p class="fruit">人數:{{room.num}}</p>
                </div>
                <div class="behavior pick">直播</div>
                <div class="goto"><img src="../static/images/arrow1.png" alt=""></div>
            </div>
        </div>
    </div>
    <script>
    apiready = function(){
        init();
        new Vue({
            el:"#app",
            data(){
                return {
          rooms:[{"avatar":"../static/images/avatar.png",name:"房間名稱",num:5}],
                    prev:{name:"",url:"",params:{}},
                    current:{name:"live",url:"live_list.html",params:{}},
                }
            },
      created(){

      },
            methods:{
        add_room(){

        },
        goto_home(){
          // 退出當前頁面
          this.game.outFrame("live","live_list.html", this.current);
        },
            }
        });
    }
    </script>
</body>
</html>

房間列表頁面初始化:live_list.html

2.房間列表頁面CSS樣式

.room_list{
  position: absolute;
  top: 18rem;
}

3.前端獲取後端傳過來的直播流列表:get_room_list

獲取服務端的直播流列表, live_list程式碼:

<!DOCTYPE html>
<html>
<head>
    <title>房間列表</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta charset="utf-8">
    <link rel="stylesheet" href="../static/css/main.css">
    <script src="../static/js/vue.js"></script>
    <script src="../static/js/axios.js"></script>
    <script src="../static/js/main.js"></script>
    <script src="../static/js/uuid.js"></script>
    <script src="../static/js/settings.js"></script>
</head>
<body>
    <div class="app user setting" id="app">
        <div class="bg">
      <img src="../static/images/rooms_bg.png">
    </div>
        <img class="back" @click="goto_home" src="../static/images/user_back.png" alt="">
        <div class="add_friend_btn" @click="add_room">
            <img src="../static/images/add_room.png" alt="">
        </div>
    <div class="friends_list room_list">
            <div class="item" v-for="room in rooms">
                <div class="avatar">
                    <img class="user_avatar" :src="room.user && settings.static_url+room.user.avatar" alt="">
                </div>
                <div class="info">
                    <p class="username">{{room.room_name}}</p>
                    <p class="fruit">人數:{{room.clients_number}}</p>
                </div>
                <div class="behavior pick" v-if="room.status">直播</div>
                <div class="goto" @click="goto_live(room.id,room.name)"><img src="../static/images/arrow1.png" alt=""></div>
            </div>
        </div>
    </div>
    <script>
    apiready = function(){
        init();
        new Vue({
            el:"#app",
            data(){
                return {
          rooms:[], // 房間列表
                    prev:{name:"",url:"",params:{}},
                    current:{name:"live",url:"live_list.html",params:{}},
                }
            },
      created(){
        this.get_room_list();
      },
            methods:{
        get_room_list(){
          var token = this.game.get("access_token") || this.game.fget("access_token");
          this.axios.post("",{
            "jsonrpc": "2.0",
            "id": this.uuid(),
            "method": "Live.stream.list",
            "params": {}
          },{
            headers:{
              Authorization: "jwt " + token,
            }
          }).then(response=>{
            if(parseInt(response.data.result.errno)==1000){
              this.rooms = response.data.result.stream_list;
            }else{
                this.game.print(response.data.result.errmsg);
            }
          }).catch(error=>{
            // 網路等異常
            this.game.print(error);
          });
        },
        goto_live(room_id,stream_name){
          // 進入房間
          var pageParam = {
            name: this.current.name,
            url: this.current.url,
            room_id: room_id,
            stream_name: stream_name
          }
          this.game.goFrame("room","live.html",pageParam);
        },
        add_room(){
          
        },
        goto_home(){
          // 退出當前頁面
          this.game.outWin("live");
        },
            }
        });
    }
    </script>
</body>
</html>

前端獲取後端傳過來的直播流列表

3.創建房間

1.創建房間頁面初始化:add_room.html

當用戶點擊創建房間時,會讓用戶輸入房間名和房間密碼

當用戶輸入後點擊確定,會向後端介面發送請求,將用戶輸入的房間名和房間密碼傳遞給後端

創建房間, add_room.html, 程式碼:

<!DOCTYPE html>
<html>
<head>
    <title>創建房間</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta charset="utf-8">
    <link rel="stylesheet" href="../static/css/main.css">
    <script src="../static/js/vue.js"></script>
    <script src="../static/js/axios.js"></script>
    <script src="../static/js/main.js"></script>
    <script src="../static/js/uuid.js"></script>
    <script src="../static/js/settings.js"></script>
</head>
<body>
    <div class="app frame avatar update_password" id="app">
    <div class="box">
      <p class="title">創建房間</p>
      <img class="close" @click="close_frame" src="../static/images/close_btn1.png" alt="">
      <div class="content">
                <input class="password" type="text" v-model="name" placeholder="房間名稱....">
                <input class="password password2" type="password" v-model="password" placeholder="房間密碼....">
      </div>
      <img @click="add_room_submit" class="btn" src="../static/images/yes.png" alt="">
    </div>
    </div>
    <script>
    apiready = function(){
        init();
        new Vue({
            el:"#app",
            data(){
                return {
                    name:"",
                    password:"",
                    prev:{name:"",url:"",params:{}},
                    current:{name:"add_room",url:"add_room.html",params:{}},
                }
            },
            methods:{
        close_frame(){
          this.game.outFrame("add_room");
        },
        add_room_submit(){
                    // 提交數據
          var token = this.game.get("access_token") || this.game.fget("access_token");
          this.axios.post("",{
            "jsonrpc": "2.0",
            "id": this.uuid(),
            "method": "Live.stream",
            "params": {
                            room_name: this.name,
                            password: this.password
                        }
          },{
            headers:{
              Authorization: "jwt " + token,
            }
          }).then(response=>{
            if(parseInt(response.data.result.errno)==1000){
              this.rooms = response.data.result.stream_list;
            }else{
                this.game.print(response.data.result.errmsg);
            }
          }).catch(error=>{
            // 網路等異常
            this.game.print(error);
          });
        },
            }
        });
    }
    </script>
</body>
</html>

創建房間頁面初始化:add_room.html

2.在直播流數據表中增加房間密碼欄位

服務端介面增加房間密碼欄位,live/models.py ,程式碼:

from application.utils.models import BaseModel,db
class LiveStream(BaseModel):
    """直播流管理"""
    __tablename__ = "mf_live_stream"
    name = db.Column(db.String(255), unique=True, comment="流名稱")
    room_name = db.Column(db.String(255), default="未命名",comment="房間名稱")
    room_password = db.Column(db.String(255), default="", comment="房間密碼")
    user = db.Column(db.Integer, comment="房主")

class LiveRoom(BaseModel):
    """直播間"""
    __tablename__ = "mf_live_room"
    stream_id = db.Column(db.Integer, comment="直播流ID")
    user   = db.Column(db.Integer, comment="用戶ID")

3.後端修改創建房間介面,新增驗證密碼功能

服務端創建房間介面, 新增密碼欄位並驗證密碼才可以進入房間

用戶輸入房間名和房間密碼後,前端向後端發起請求,將輸入內容提交給後端

後端接收到房間名和房間密碼後,做如下幾件事:

1.創建直播流:,mysql中存放:用戶id/房間名/房間密碼/直播流號

2.創建房間:mysql中存放:用戶id/直播流號

live/views.py, 程式碼:

from application import jsonrpc,db
from message import ErrorMessage as message
from status import APIStatus as status
from flask_jwt_extended import jwt_required,get_jwt_identity
from application.apps.users.models import User
from .models import LiveStream,LiveRoom
from datetime import datetime
import random
@jsonrpc.method("Live.stream")
@jwt_required # 驗證jwt
def live_stream(room_name,password):
    """創建直播流"""
    current_user_id = get_jwt_identity() # get_jwt_identity 用於獲取載荷中的數據
    user = User.query.get(current_user_id)
    if user is None:
        return {
            "errno": status.CODE_NO_USER,
            "errmsg": message.user_not_exists,
        }
    # 申請創建直播流
    stream = LiveStream.query.filter(LiveStream.user==user.id).first()
    if stream is None:
        stream_name = "room_%06d%s%06d" % (
        user.id, datetime.now().strftime("%Y%m%d%H%M%S"), random.randint(100, 999999))
        stream = LiveStream(
            name=stream_name,
            user=user.id,
            room_name=room_name,
            room_password=password
        )
        db.session.add(stream)
        db.session.commit()
    else:
        stream.room_name = room_name
        stream.room_password = password
        db.session.commit()

    # 進入房間
    room = LiveRoom.query.filter(LiveRoom.user==user.id,LiveRoom.stream_id==stream.id).first()
    if room is None:
        room = LiveRoom(
            stream_id=stream.id,
            user=user.id
        )
        db.session.add(room)
        db.session.commit()

    return {
        "errno": status.CODE_OK,
        "errmsg": message.ok,
        "data":{
            "stream_name": stream.name,
            "room_name": room_name,
            "room_owner": user.id,
            "room_id": "%04d" % stream.id,
        }
    }

from .marshmallow import StreamInfoSchema
from flask import current_app
@jsonrpc.method("Live.stream.list")
@jwt_required # 驗證jwt
def list_stream():
    """房間列表"""
    current_user_id = get_jwt_identity() # get_jwt_identity 用於獲取載荷中的數據
    user = User.query.get(current_user_id)
    if user is None:
        return {
            "errno": status.CODE_NO_USER,
            "errmsg": message.user_not_exists,
            "data": {

            }
        }

    stream_list = LiveStream.query.filter(LiveStream.status==True, LiveStream.is_deleted==False).all()
    sis = StreamInfoSchema()
    data_list = sis.dump(stream_list,many=True)

    # 使用requests發送get請求
    import requests
    stream_response = requests.get(current_app.config["SRS_HTTP_API"]+"streams/")
    client_response = requests.get(current_app.config["SRS_HTTP_API"]+"clients/")
    import re,json
    stream_text = re.sub(r'[^\{\}\/\,0-9a-zA-Z\"\'\:\[\]\._]', "", stream_response.text)
    client_text = re.sub(r'[^\{\}\/\,0-9a-zA-Z\"\:\[\]\._]', "", client_response.text)
    stream_dict = json.loads(stream_text)
    client_dict = json.loads(client_text)
    for data in data_list:
        data["status"] = False
        for stream in stream_dict["streams"]:
            if data["name"] == stream["name"]:
                data["status"] = stream["publish"]["active"]
                break
        data["clients_number"] = 0
        for client in client_dict["clients"]:
            if data["name"] == client["url"].split("/")[-1]:
                data["clients_number"]+=1
            if client["publish"] and "/live/"+data["name"]==client["url"]:
                data["user"]["ip"] = client["ip"]
    return {
        "errno": status.CODE_OK,
        "errmsg": message.ok,
        "stream_list": data_list
    }

服務端提供創建房間介面

4.前端判斷房間是否存在密碼,如存在密碼必須正確輸入密碼才可進入房間

客戶端中判定當房間存在密碼時, 用戶必須輸入密碼成功以後才可以進入房間, live_list.html程式碼:

<!DOCTYPE html>
<html>
<head>
    <title>房間列表</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta charset="utf-8">
    <link rel="stylesheet" href="../static/css/main.css">
    <script src="../static/js/vue.js"></script>
    <script src="../static/js/axios.js"></script>
    <script src="../static/js/main.js"></script>
    <script src="../static/js/uuid.js"></script>
    <script src="../static/js/settings.js"></script>
</head>
<body>
    <div class="app user setting" id="app">
        <div class="bg">
      <img src="../static/images/rooms_bg.png">
    </div>
        <img class="back" @click="goto_home" src="../static/images/user_back.png" alt="">
        <div class="add_friend_btn" @click="add_room">
            <img src="../static/images/add_room.png" alt="">
        </div>
    <div class="friends_list room_list">
            <div class="item" v-for="room in rooms" @click="goto_live(room.id,room.name,room.room_password)">
                <div class="avatar">
                    <img class="user_avatar" :src="room.user && settings.static_url+room.user.avatar" alt="">
                </div>
                <div class="info">
                    <p class="username">{{room.room_name}}</p>
                    <p class="fruit">人數:{{room.clients_number}}</p>
                </div>
                <div class="behavior pick" v-if="room.status">直播</div>
                <div class="goto"><img src="../static/images/arrow1.png" alt=""></div>
            </div>
        </div>
    </div>
    <script>
    apiready = function(){
        init();
        new Vue({
            el:"#app",
            data(){
                return {
          rooms:[], // 房間列表
                    prev:{name:"",url:"",params:{}},
                    current:{name:"live",url:"live_list.html",params:{}},
                }
            },
      created(){
        this.get_room_list();
      },
            methods:{
        get_room_list(){
          var token = this.game.get("access_token") || this.game.fget("access_token");
          this.axios.post("",{
            "jsonrpc": "2.0",
            "id": this.uuid(),
            "method": "Live.stream.list",
            "params": {}
          },{
            headers:{
              Authorization: "jwt " + token,
            }
          }).then(response=>{
            if(parseInt(response.data.result.errno)==1000){
              this.rooms = response.data.result.stream_list;
            }else{
                this.game.print(response.data.result.errmsg);
            }
          }).catch(error=>{
            // 網路等異常
            this.game.print(error);
          });
        },
        goto_live(room_id,stream_name,room_password){
          // 驗證密碼
          if(room_password != null){
            api.prompt({
                title:"請輸入房間密碼!",
                buttons: ['確定', '取消'],
            }, (ret, err)=>{
                if( ret.text == room_password ){
                    this.goto_room(room_id,stream_name);
                }else {
                  alert("密碼錯誤!");
                }
            });
          }else{
            this.goto_room(room_id,stream_name);
          }
        },
        goto_room(room_id,stream_name){
          // 進入房間
          var pageParam = {
            name: this.current.name,
            url: this.current.url,
            room_id: room_id,
            stream_name: stream_name
          }
          this.game.goFrame("room","live.html",pageParam);
        },
        add_room(){
          this.game.goFrame("add_room","add_room.html",this.current,null,{
              type:"push",
              subType:"from_top",
              duration:300
          });

          api.addEventListener({
              name: 'add_room_success'
          }, (ret, err)=>{
              if( ret ){
                   this.game.print("創建房間成功");
              }
          });


        },
        goto_home(){
          // 退出當前頁面
          this.game.outWin("live");
        },
            }
        });
    }
    </script>
</body>
</html>

前端判斷房間是否存在密碼,如果存在密碼,必須正確輸入密碼才可以進入房間

5.當用戶點擊返回鍵時,關閉推流

1.live_list.html

監聽當前窗口下的任意一個幀頁面點擊返回鍵(keyback)的操作

當用戶點擊返回鍵的時候,告知(sendEvent)直播間關閉直播推流

<!DOCTYPE html>
<html>
<head>
    <title>房間列表</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta charset="utf-8">
    <link rel="stylesheet" href="../static/css/main.css">
    <script src="../static/js/vue.js"></script>
    <script src="../static/js/axios.js"></script>
    <script src="../static/js/main.js"></script>
    <script src="../static/js/uuid.js"></script>
    <script src="../static/js/settings.js"></script>
</head>
<body>
    <div class="app user setting" id="app">
        <div class="bg">
      <img src="../static/images/rooms_bg.png">
    </div>
        <img class="back" @click="goto_home" src="../static/images/user_back.png" alt="">
        <div class="add_friend_btn" @click="add_room">
            <img src="../static/images/add_room.png" alt="">
        </div>
    <div class="friends_list room_list">
            <div class="item" v-for="room in rooms" @click="goto_live(room.id,room.name,room.room_password)">
                <div class="avatar">
                    <img class="user_avatar" :src="room.user && settings.static_url+room.user.avatar" alt="">
                </div>
                <div class="info">
                    <p class="username">{{room.room_name}}</p>
                    <p class="fruit">人數:{{room.clients_number}}</p>
                </div>
                <div class="behavior pick" v-if="room.status">直播</div>
                <div class="goto"><img src="../static/images/arrow1.png" alt=""></div>
            </div>
        </div>
    </div>
    <script>
    apiready = function(){
        init();
        new Vue({
            el:"#app",
            data(){
                return {
          rooms:[], // 房間列表
                    prev:{name:"",url:"",params:{}},
                    current:{name:"live",url:"live_list.html",params:{}},
                }
            },
      created(){
        this.get_room_list();
      },
            methods:{
        get_room_list(){
          var token = this.game.get("access_token") || this.game.fget("access_token");
          this.axios.post("",{
            "jsonrpc": "2.0",
            "id": this.uuid(),
            "method": "Live.stream.list",
            "params": {}
          },{
            headers:{
              Authorization: "jwt " + token,
            }
          }).then(response=>{
            if(parseInt(response.data.result.errno)==1000){
              this.rooms = response.data.result.stream_list;
            }else{
                this.game.print(response.data.result.errmsg);
            }
          }).catch(error=>{
            // 網路等異常
            this.game.print(error);
          });
        },
        goto_live(room_id,stream_name,room_password){
          // 驗證密碼
          if(room_password != null){
            api.prompt({
                title:"請輸入房間密碼!",
                buttons: ['確定', '取消'],
            }, (ret, err)=>{
                if( ret.text == room_password ){
                    this.goto_room(room_id,stream_name);
                }else {
                  alert("密碼錯誤!");
                }
            });
          }else{
            this.goto_room(room_id,stream_name);
          }
        },
        goto_room(room_id,stream_name){
          // 進入房間
          var pageParam = {
            name: this.current.name,
            url: this.current.url,
            room_id: room_id,
            stream_name: stream_name
          }
                    // 當用戶在當前窗口下的任何一個幀頁面中點擊返回鍵,發起全局通知
                    api.addEventListener({
                        name: 'keyback'
                    }, (ret, err)=>{
                          // 告知直播間,關閉直播推流
                            api.sendEvent({
                                name: 'live_page_out',
                                extra: {

                                }
                            });
                    });

          this.game.goFrame("room","live.html",pageParam);
        },
        add_room(){
          this.game.goFrame("add_room","add_room.html",this.current,null,{
              type:"push",
              subType:"from_top",
              duration:300
          });

          api.addEventListener({
              name: 'add_room_success'
          }, (ret, err)=>{
              if( ret ){
                  this.game.print("創建房間成功");
                  // 進入房間
                  this.goto_room(ret.value.room_id,ret.value.stream_name);
              }
          });


        },
        goto_home(){
          // 退出當前頁面
          this.game.outWin("live");
        },
            }
        });
    }
    </script>
</body>
</html>

live_list.html監聽退出動作,並告知直播間關閉直播推流

2.live.html

監聽用戶是否有返回的動作,如果監聽到,關閉攝影機採集功能和直播推流

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
  <link rel="stylesheet" href="../static/css/main.css">
  <script src="../static/js/vue.js"></script>
    <script src="../static/js/axios.js"></script>
    <script src="../static/js/main.js"></script>
    <script src="../static/js/uuid.js"></script>
    <script src="../static/js/settings.js"></script>
</head>
<body>
  <div class="app" id="app">
    <br><br><br><br>
    <br><br><br><br>
    <button @click="start_live">我要開播</button>
    <button @click="viewer">我是觀眾</button>
  </div>
  <script>
    apiready = function(){
    init();
        new Vue({
            el:"#app",
            data(){
                return {
          music_play:true,  //
          stream_name:"",   // 直播流名稱
                    prev:{name:"",url:"",params:{}}, //
                    current:{name:"live",url:"live_list.html","params":{}}, //
                }
            },
      created(){
        this.stream_name = api.pageParam.stream_name;
      },
            methods:{
        viewer(){
          // 觀看直播
          var obj = api.require('playModule');
          obj.play({
              rect:
              {   x:  0,
                  y : 0,
                  w : 360,
                  h: 1080,
              },
              fixedOn: api.frameName,
              title: 'test',
              scalingMode:2,
              url: this.settings.live_stream_server+this.stream_name,
              defaultBtn: false,
              enableFull : false,
              isTopView : false,
              isLive: true,
              placeholderText:true,
          }, (ret, err)=>{
            this.game.print(ret);
          });
        },
        liver(){
          var token = this.game.get("access_token") || this.game.fget("access_token");
                    this.axios.post("",{
                            "jsonrpc": "2.0",
                            "id": this.uuid(),
                            "method": "Live.stream",
                            "params": {
                                "room_name": "愛的直播間"
                            }
                        },{
                            headers:{
                                Authorization: "jwt " + token,
                            }
                        }).then(response=>{
              var message = response.data.result;
              if(parseInt(message.errno)==1005){
                this.game.goWin("user","login.html", this.current);
              }
                            if(parseInt(message.errno)==1000){
                this.stream_name = message.data.stream_name;
                this.game.print(this.stream_name)
                            }else{
                                this.game.print(response.data);
                            }
                        }).catch(error=>{
                            // 網路等異常
                            this.game.print(error);
                        });
        },
        start_live(){
          // 開始直播
          var acLive = api.require('acLive');
          // 打開攝影機採集影片資訊
          acLive.open({
              camera:0, // 1為前置攝影機, 0為後置攝影機,默認1
              rect : {  // 採集畫面的位置和尺寸
                  x : 0,
                  y : 0,
                  w : 360,
                  h : 1080,
              }
          },(ret, err)=>{
              this.game.print(ret);
              // 開啟美顏
              acLive.beautyFace();
              // 開始推流
              acLive.start({
                  url: this.settings.live_stream_server+this.stream_name // t1 就是流名稱,可以理解為直播的房間號
              },(ret, err)=>{
                  this.game.print(ret); // 狀態如果為2則表示連接成功,其他都表示不成功
              });
          });
          // 監聽用戶是否點擊了返回鍵按鈕,如果點擊了,則關閉推流和攝影機資訊採集功能
          api.addEventListener({
              name:'live_page_out'
          },()=>{
              acLive.close();
              acLive.end();
          });

        }
            }
        })
    }
    </script>
</body>
</html>

live.html監聽用戶是否有返回的動作,如果監聽到,則關閉攝影機採集功能和直播推流