Поделиться через


Управление вызовами на устройстве связи Bluetooth по умолчанию (HTML)

[ Эта статья адресована разработчикам приложений среды выполнения Windows для Windows 8.x и Windows Phone 8.x. В случае разработки приложений для Windows 10 см. раздел последняя документация]

В этом учебнике показано, как настроить обработку звонков при помощи устройства связи Bluetooth по умолчанию.

Что необходимо знать

Технологии

  • Windows Runtime

Необходимые условия

  • Вам необходимо знать HTML, Javascript и уметь обращаться с событиями Windows и обработкой событий.
  • Для запуска данного образца необходим компьютер с установленным модулем Bluetooth, работающий под управлением Windows 8 или более поздней операционной системы.

Инструкции

Этап 1: Код файла Default.html

В образце кода CallControl для форматирования экрана с использованием элементов пользовательского интерфейса, позволяющих поработать с соответствующими им функциями, используется следующий HTML-сценарий.

  • В образце CallControl используется следующий HTML-код:
<!DOCTYPE html>
<html>
<head>
    <title>Call Control</title>
    
    <!-- WinJS references -->
    <link href="winjs/css/ui-light.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="WinJS/js/base.js"></script>
    <script type="text/javascript" src="WinJS/js/ui.js"></script>
    <script type="text/javascript" src="WinJS/js/wwaapp.js"></script>

    <!-- SDK Base references -->
    <link rel="stylesheet" type="text/css" href="css/base-sdk.css" />
    <script type="text/javascript" src="base-sdk.js"></script>

    <!-- Sample references -->
    <link rel="stylesheet" type="text/css" href="css/program.css" />
    <script type="text/javascript" src="program.js"></script>

</head>
<body role="application">
    <div id="rootGrid">
        <div id="header" role="contentinfo">
        </div>
        <div id="content">
            <h1>
                Call Control</h1>
            <h2 id="inputLabel">
                Input</h2>
            <div id="input" role="main" aria-labelledby="inputLabel">
                <div class="options">
                    <h3 id="listLabel">
                        Select scenario:</h3>
                    <select size="4" id="scenarios" aria-labelledby="listLabel">
                        <option selected="selected" value="1">1) Call Controls</option>
                    </select>
                </div>
                <div class="details" role="region" aria-labelledby="descLabel" aria-live="assertive">
                    <h3 id="descLabel">
                        Description:</h3>
                    <!-- Scenario 1 Input -->
                    <div class="item" id="scenario1Input">
                        <p>
                            To use this sample, ensure you have a bluetooth device and press the initialize
                            the call control button. After initialization you will be able to simulate an incoming
                            call by pressing the indicate phone call button. Use your bluetooth device to answer
                            and hang up the call. Redial and dial should work after initialization. Some devices
                            require a stream to be opened so a file will start playing to the default communications
                            device.
                        </p>
                        <button class="action" id="scenario1Initialize">
                            Initialize Call Buttons</button>
                        <button class="action secondary" id="scenario1Ring" disabled="disabled">
                            Indicate Phone Call</button>
                        <br />
                        <br />
                    </div>
                </div>
            </div>
            <div class="clear">
            </div>
            <h2 id="outputLabel">
                Output</h2>
            <div id="output" role="region" aria-labelledby="outputLabel" aria-live="assertive">
                <div id="statusMessage">
                </div>
                <!-- Scenario 1 Output -->
                <div class="item" id="scenario1Output">
                    <audio id="audiotag" src="folk_rock.mp3" msaudiocategory="communications"
                        msaudiodevicetype="communications" loop>
                    </audio>
                </div>
            </div>
        </div>
        <div id="footer" role="contentinfo">
        </div>
    </div>
</body>
</html>

Этап 2: Код файла Default.js

В процессе инициализации в образце CallControl настраиваются приемники событий, которые привязываются к обработчикам событий для отклика на нажатие кнопок, включая кнопку ответа на вызов и кнопку сброса вызова.

  • Код JavaScript, используемый в образце CallControl:
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved

/// <reference path="base-sdk.js" />

(function () {

    // Initialize the call control object here using the default bluetooth communications device
    var callControls = null;
    var callToken;
    var audiotag;

    function id(elementId) {
        return document.getElementById(elementId);
    }

    function initDevice() {
        if (!callControls) {
            try {
                callControls = Windows.Media.Devices.CallControl.getDefault();

                if (callControls) {
                    // Add the event listener to listen for the various button presses
                    callControls.addEventListener("answerrequested", answerButton, false);
                    callControls.addEventListener("hanguprequested", hangupButton, false);
                    callControls.addEventListener("audiotransferrequested", audiotransferButton, false);
                    callControls.addEventListener("redialrequested", redialButton, false);
                    callControls.addEventListener("dialrequested", dialButton, false);

                    sdkSample.displayStatus("Call Controls Initialized");
                    id("scenario1Ring").disabled = false;
                } else {
                    sdkSample.displayError("No Bluetooth device detected.");
                }
            }
            catch (e) {                
                sdkSample.displayError("No Bluetooth device detected.");
            }
        }
    }

    function newIncomingCall() {
        // Indicate a new incoming call and ring the headset.
        callToken = callControls.indicateNewIncomingCall(true, "5555555555");
        sdkSample.displayStatus("Call Token: " + callToken);
    }

    function answerButton() {
        // When the answer button is pressed indicate to the device that the call was answered
        // and start a song on the headset (this is done by streaming music to the bluetooth
        // device in this sample)
        sdkSample.displayStatus("Answer requested: " + callToken);
        callControls.indicateActiveCall(callToken);
        audiotag = document.getElementById("audiotag");
        audiotag.play();
    }

    function hangupButton() {
        // Hang up request received.  The application should end the active call and stop
        // streaming to the headset
        sdkSample.displayStatus("Hangup requested");
        callControls.endCall(callToken);
        audiotag = document.getElementById("audiotag");
        audiotag.pause();
    }

    function audiotransferButton() {
        // Handle the audio transfer request here
        sdkSample.displayStatus("Audio Transfer requested");
    }

    function redialButton(redialRequestedEventArgs) {
        // Handle the redial request here.  Indicate to the device that the request was handled.
        sdkSample.displayStatus("Redial requested");
        redialRequestedEventArgs.handled = true;
    }

    function dialButton(dialRequestedEventArgs) {
        // A device may send a dial request by either sending a URI or if it is a speed dial,
        // an integer with the number to dial.
        if (typeof(dialRequestedEventArgs.contact) === "number") {
            sdkSample.displayStatus("Dial requested: " + dialRequestedEventArgs.contact);
            dialRequestedEventArgs.handled = true;
        }
        else {
            sdkSample.displayStatus("Dial requested: " + dialRequestedEventArgs.contact.schemeName + ":" +
            dialRequestedEventArgs.contact.path);
            dialRequestedEventArgs.handled = true;
        }
    }

    function initialize() {
        id("scenario1Initialize").addEventListener("click", initDevice, false);
        id("scenario1Ring").addEventListener("click", newIncomingCall, false);
        id("scenarios").addEventListener("change", onScenarioChanged, false);
    }

    function onScenarioChanged() {
        sdkSample.displayStatus("");
    }

    document.addEventListener("DOMContentLoaded", initialize, false);
})();

Этап 3: Запуск и тестирование образца CallControl

  • Подробные инструкции по сборке, запуску и тестированию данного образца включены в его описание. Инструкции по сборке примера и другую информацию о нем см. в примере Call Control.

Примечания

Для некоторых устройств необходимо, чтобы до начала воспроизведения звукового файла на устройстве связи по умолчанию был открыт аудиопоток,.

Инструкции для разработчиков и рекомендации по управлению звонками в приложении Магазина Windows см. в разделе Правила разработки приложений, поддерживающих аудио

Связанные разделы

Образец управления звонками

Правила разработки приложений, поддерживающих аудио