8个鲜为人知但很实用的Web API(上)

简介: 8个鲜为人知但很实用的Web API(上)

大家好,我是 CUGGZ。

在 Web API 中,有非常有用的对象、属性和函数可用于执行小到访问 DOM 这样的小任务,大到处理音频、视频这样的复杂任务。常见的 API 有 Canvas、Web Worker、History、Fetch 等。下面就来看一些不常见但很实用的 Web API!


全文概览:

  1. Web Audio API
  2. Fullscreen API
  3. Web Speech API
  4. Web Bluetooth API
  5. Vibration API
  6. Broadcast Channel API
  7. Clipboard API
  8. Web Share API


1. Web Audio API


Audio API 允许我们在 Web 上操作音频流,它可以用于 Web 上的音频源添加效果和过滤器。音频源可以来自、视频/音频源文件或音频网络流。

下面来看一个例子:


<body>
    <header>
        <h2>Web APIs<h2>
    </header>
    <div class="web-api-cnt">
        <div class="web-api-card">
            <div class="web-api-card-head">
                Demo - Audio
            </div>
            <div class="web-api-card-body">
                <div id="error" class="close"></div>
                <div>
                    <audio controls src="./audio.mp3" id="audio"></audio>
                </div>
                <div>
                    <button onclick="audioFromAudioFile.init()">Init</button>
                    <button onclick="audioFromAudioFile.play()">Play</button>
                    <button onclick="audioFromAudioFile.pause()">Pause</button>
                    <button onclick="audioFromAudioFile.stop()">Stop</button>
                </div>
                <div>
                    <span>Vol: <input onchange="audioFromAudioFile.changeVolume()" type="range" id="vol" min="1" max="2" step="0.01" value="1" /></span>
                    <span>Pan: <input onchange="audioFromAudioFile.changePan()" type="range" id="panner" min="-1" max="1" step="0.01" value="0" /></span>
                </div>
            </div>
        </div>
    </div>
</body>
<script>
    const l = console.log
    let audioFromAudioFile = (function() {
        var audioContext
        var volNode
        var pannerNode
        var mediaSource
        function init() {
            l("Init")
        try {
                audioContext = new AudioContext()        
                mediaSource = audioContext.createMediaElementSource(audio)
                volNode = audioContext.createGain()
                volNode.gain.value = 1
                pannerNode = new StereoPannerNode(audioContext, { pan:0 })
                mediaSource.connect(volNode).connect(pannerNode).connect(audioContext.destination)
            }
            catch(e) {
                error.innerHTML = "此设备不支持 Web Audio API"
                error.classList.remove("close")
            }
        }
        function play() {
            audio.play()            
        }
        function pause() {
            audio.pause()
        }
        function stop() {
            audio.stop()            
        }
        function changeVolume() {
            volNode.gain.value = this.value
            l("Vol Range:",this.value)
        }
        function changePan() {
            pannerNode.gain.value = this.value
            l("Pan Range:",this.value)
        }
        return {
            init,
            play,
            pause,
            stop,
            changePan,
            changeVolume
        }
    })()
</script>


这个例子中将音频从 元素传输到 AudioContext,声音效果(如平移)在被输出到音频输出(扬声器)之前被添加到音频源。

按钮 Init 在单击时调用 init 函数。 这将创建一个 AudioContext 实例并将其设置为 audioContext。 接下来,它创建一个媒体源 createMediaElementSource(audio),将音频元素作为音频源传递。音量节点 volNodecreateGain 创建,可以用来调节音量。接下来使用 StereoPannerNode 设置平移效果,最后将节点连接至媒体源。

1.webp.jpg

点击按钮(Play、Pause、Stop)可以播放、暂停和停止音频。页面有一个音量和平移的范围滑块,滑动滑块就可以调节音频的音量和平移效果。

相关资源:


2. Fullscreen API


Fullscreen API 用于在 Web 应用程序中开启全屏模式,使用它就可以在全屏模式下查看页面/元素。在安卓手机中,它会溢出浏览器窗口和安卓顶部的状态栏(显示网络状态、电池状态等的地方)。

Fullscreen API 方法:

  • requestFullscreen:系统上以全屏模式显示所选元素,会关闭其他应用程序以及浏览器和系统 UI 元素。
  • exitFullscreen:退出全屏模式并切换到正常模式。

下面来看一个常见的例子,使用全屏模式观看视频::

<body>
    <header>
        <h2>Web APIs<h2>
    </header>
    <div class="web-api-cnt">
        <div class="web-api-card">
        <div class="web-api-card-head">
            Demo - Fullscreen
        </div>
        <div class="web-api-card-body">
        <div id="error" class="close"></div>
        <div>
            This API makes fullscreen-mode of our webpage possible. It lets you select the Element you want to view in fullscreen-mode, then it shuts off the browsers window features like URL bar, the window pane, and presents the Element to take the entire width and height of the system.
In Android phones, it will remove the browsers window and the Android UI where the network status, battery status are displayed, and display the Element in full width of the Android system.
        </div>
        <div class="video-stage">
            <video id="video" src="./video.mp4"></video>
            <button onclick="toggle()">Toogle Fullscreen</button>
        </div>
        <div>
            This API makes fullscreen-mode of our webpage possible. It lets you select the Element you want to view in fullscreen-mode, then it shuts off the browsers window features like URL bar, the window pane, and presents the Element to take the entire width and height of the system.
In Android phones, it will remove the browsers window and the Android UI where the network status, battery status are displayed, and display the Element in full width of the Android system.
        </div>
        </div>
        </div>
    </div>
</body>
<script>
    const l =console.log
    function toggle() {
        const videoStageEl = document.querySelector(".video-stage")
        if(videoStageEl.requestFullscreen) {
            if(!document.fullscreenElement){
                videoStageEl.requestFullscreen()
            }
            else {
                document.exitFullscreen()
            }
        } else {
            error.innerHTML = "此设备不支持 Fullscreen API"
            error.classList.remove("close")        
        }
    }
</script>

可以看到,video 元素在 div#video-stage 元素中,带有一个按钮 Toggle Fullscreen。2.webp.jpg

当点击按钮切换全屏时,我们想让元素 div#video-stage 全屏显示。toggle 函数的实现如下:

function toggle() {
  const videoStageEl = document.querySelector(".video-stage")
  if(!document.fullscreenElement)
    videoStageEl.requestFullscreen()
  else
    document.exitFullscreen()
}

这里通过 querySelector 查找 div#video-stage 元素并将其 HTMLDivElement 实例保存在 videoStageEl 上。

然后,使用 document.fullsreenElement 属性来确定 document 是否是全屏的,所以可以在 videoStageEl 上调用 requestFullscreen()。 这将使 div#video-stage 占据整个设备的视图。

如果在全屏模式下点击 Toggle Fullscreen 按钮,就会在 document 上调用 exitFullcreen,这样 UI 视图就会返回到普通视图(退出全屏)。

2.webp (1).jpg

相关资源:


3. Web Speech API


Web Speech API 提供了将语音合成和语音识别添加到 Web 应用程序的功能。使用此 API,我们将能够向 Web 应用程序发出语音命令,就像在 Android 上通过其 Google Speech 或在 Windows 中使用 Cortana 一样。

下面来看一个简单的例子,使用 Web Speech API 实现文字转语音和语音转文字:

<body>
    <header>
        <h2>Web APIs<h2>
    </header>
    <div class="web-api-cnt">
        <div id="error" class="close"></div>
        <div class="web-api-card">
            <div class="web-api-card-head">
                Demo - Text to Speech
            </div>
            <div class="web-api-card-body">
                <div>
                    <input placeholder="Enter text here" type="text" id="textToSpeech" />
                </div>
                <div>
                    <button onclick="speak()">Tap to Speak</button>
                </div>
            </div>
        </div>
        <div class="web-api-card">
            <div class="web-api-card-head">
                Demo - Speech to Text
            </div>
            <div class="web-api-card-body">
                <div>
                    <textarea placeholder="Text will appear here when you start speeaking." id="speechToText"></textarea>
                </div>
                <div>
                    <button onclick="tapToSpeak()">Tap and Speak into Mic</button>
                </div>
            </div>
        </div>
    </div>
</body>
<script>
    try {
        var speech = new SpeechSynthesisUtterance()
        var SpeechRecognition = SpeechRecognition;
        var recognition = new SpeechRecognition()
    } catch(e) {
        error.innerHTML = "此设备不支持 Web Speech API"
        error.classList.remove("close")                
    }
    function speak() {
        speech.text = textToSpeech.value
        speech.volume = 1
        speech.rate=1
        speech.pitch=1
        window.speechSynthesis.speak(speech)
    }
    function tapToSpeak() {
        recognition.onstart = function() { }
        recognition.onresult = function(event) {
            const curr = event.resultIndex
            const transcript = event.results[curr][0].transcript
            speechToText.value = transcript
        }
        recognition.onerror = function(ev) {
            console.error(ev)
        }
        recognition.start()
    }
</script>

3.webp.jpg

第一个演示 Demo - Text to Speech 演示了使用这个 API 和一个简单的输入字段,接收输入文本和一个按钮来执行语音操作。

function speak() {
  const speech = new SpeechSynthesisUtterance()
  speech.text = textToSpeech.value
  speech.volume = 1
  speech.rate = 1
  speech.pitch = 1
  window.speechSynthesis.speak(speech)
}

它实例化了 SpeechSynthesisUtterance() 对象,将文本设置为从输入框中输入的文本中朗读。 然后,使用 speech 对象调用 SpeechSynthesis#speak 函数,在扬声器中说出输入框中的文本。

第二个演示 Demo - Speech to Text 将语音识别为文字。 点击 Tap and Speak into Mic 按钮并对着麦克风说话,我们说的话会被翻译成文本输入框中的内容。

点击 Tap and Speak into Mic 按钮会调用 tapToSpeak 函数:

function tapToSpeak() {
  var SpeechRecognition = SpeechRecognition;
  const recognition = new SpeechRecognition()
  recognition.onstart = function() { }
  recognition.onresult = function(event) {
    const curr = event.resultIndex
    const transcript = event.results[curr][0].transcript
    speechToText.value = transcript
  }
  recognition.onerror = function(ev) {
    console.error(ev)
  }
  recognition.start()
}

这里实例化了 SpeechRecognition,然后注册事件处理程序和回调。语音识别开始时调用 onstart,发生错误时调用 onerror。 每当语音识别捕获一条线时,就会调用 onresult

onresult 回调中,提取内容并将它们设置到 textarea 中。 因此,当我们对着麦克风说话时,文字会出现在 textarea 内容中。

相关资源:


4. Web Bluetooth API


Bluetooth API 让我们可以访问手机上的低功耗蓝牙设备,并使用它将网页上的数据共享到另一台设备。

基本 API 是 navigator.bluetooth.requestDevice。 调用它将使浏览器提示用户使用设备选择器,用户可以在其中选择一个设备或取消请求。navigator.bluetooth.requestDevice 需要一个强制对象。 此对象定义过滤器,用于返回与过滤器匹配的蓝牙设备。

下面来看一个简单的例子,使用 navigator.bluetooth.requestDevice API 从 BLE 设备检索基本设备信息:

<body>
  <header>
    <h2>Web APIs<h2>
      </header>
      <div class="web-api-cnt">
        <div class="web-api-card">
          <div class="web-api-card-head">
            Demo - Bluetooth
          </div>
          <div class="web-api-card-body">
            <div id="error" class="close"></div>
            <div>
              <div>Device Name: <span id="dname"></span></div>
              <div>Device ID: <span id="did"></span></div>
              <div>Device Connected: <span id="dconnected"></span></div>
            </div>
            <div>
              <button onclick="bluetoothAction()">Get BLE Device</button>
            </div>
          </div>
        </div>
      </div>
      </body>
    <script>
      function bluetoothAction(){
        if(navigator.bluetooth) {
          navigator.bluetooth.requestDevice({
            acceptAllDevices: true
          }).then(device => {            
            dname.innerHTML = device.name
            did.innerHTML = device.id
            dconnected.innerHTML = device.connected
          }).catch(err => {
            error.innerHTML = "Oh my!! Something went wrong."
            error.classList.remove("close")
          })
        } else {
          error.innerHTML = "Bluetooth is not supported."            
          error.classList.remove("close")
        }
      }
</script>

4.webp.jpg

这里会显示设备信息。 单击 Get BLE Device 按钮会调用 bluetoothAction 函数:

function bluetoothAction(){
  navigator.bluetooth.requestDevice({
    acceptAllDevices: true
  }).then(device => {            
    dname.innerHTML = device.name
    did.innerHTML = device.id
    dconnected.innerHTML = device.connected
  }).catch(err => {
    console.error("Oh my!! Something went wrong.")
  })
}

bluetoothAction 函数调用带有 acceptAllDevices:true 选项的 navigator.bluetooth.requestDevice API,这将使其扫描并列出所有附近的蓝牙活动设备。 它返回了一个 promise,所以将它解析为从回调函数中获取一个参数 device,这个 device 参数将保存列出的蓝牙设备的信息。这是我们使用其属性在设备上显示信息的地方。

相关资源:


8个鲜为人知但很实用的Web API(下)https://developer.aliyun.com/article/1411363

相关实践学习
达摩院智能语音交互 - 声纹识别技术
声纹识别是基于每个发音人的发音器官构造不同,识别当前发音人的身份。按照任务具体分为两种: 声纹辨认:从说话人集合中判别出测试语音所属的说话人,为多选一的问题 声纹确认:判断测试语音是否由目标说话人所说,是二选一的问题(是或者不是) 按照应用具体分为两种: 文本相关:要求使用者重复指定的话语,通常包含与训练信息相同的文本(精度较高,适合当前应用模式) 文本无关:对使用者发音内容和语言没有要求,受信道环境影响比较大,精度不高 本课程主要介绍声纹识别的原型技术、系统架构及应用案例等。 讲师介绍: 郑斯奇,达摩院算法专家,毕业于美国哈佛大学,研究方向包括声纹识别、性别、年龄、语种识别等。致力于推动端侧声纹与个性化技术的研究和大规模应用。
相关文章
|
Java API 数据库
构建RESTful API已经成为现代Web开发的标准做法之一。Spring Boot框架因其简洁的配置、快速的启动特性及丰富的功能集而备受开发者青睐。
【10月更文挑战第11天】本文介绍如何使用Spring Boot构建在线图书管理系统的RESTful API。通过创建Spring Boot项目,定义`Book`实体类、`BookRepository`接口和`BookService`服务类,最后实现`BookController`控制器来处理HTTP请求,展示了从基础环境搭建到API测试的完整过程。
282 4
|
XML JSON API
ServiceStack:不仅仅是一个高性能Web API和微服务框架,更是一站式解决方案——深入解析其多协议支持及简便开发流程,带您体验前所未有的.NET开发效率革命
【10月更文挑战第9天】ServiceStack 是一个高性能的 Web API 和微服务框架,支持 JSON、XML、CSV 等多种数据格式。它简化了 .NET 应用的开发流程,提供了直观的 RESTful 服务构建方式。ServiceStack 支持高并发请求和复杂业务逻辑,安装简单,通过 NuGet 包管理器即可快速集成。示例代码展示了如何创建一个返回当前日期的简单服务,包括定义请求和响应 DTO、实现服务逻辑、配置路由和宿主。ServiceStack 还支持 WebSocket、SignalR 等实时通信协议,具备自动验证、自动过滤器等丰富功能,适合快速搭建高性能、可扩展的服务端应用。
861 3
|
10月前
|
人工智能 搜索推荐 IDE
突破网页数据集获取难题:Web Unlocker API 助力 AI 训练与微调数据集全方位解决方案
本文介绍了Web Unlocker API、Web-Scraper和SERP API三大工具,助力解决AI训练与微调数据集获取难题。Web Unlocker API通过智能代理和CAPTCHA绕过技术,高效解锁高防护网站数据;Web-Scraper支持动态内容加载,精准抓取复杂网页信息;SERP API专注搜索引擎结果页数据抓取,适用于SEO分析与市场研究。这些工具大幅降低数据获取成本,提供合规保障,特别适合中小企业使用。粉丝专属体验入口提供2刀额度,助您轻松上手!
508 2
|
人工智能 前端开发 API
Gemini Coder:基于 Google Gemini API 的开源 Web 应用生成工具,支持实时编辑和预览
Gemini Coder 是一款基于 Google Gemini API 的 AI 应用生成工具,支持通过文本描述快速生成代码,并提供实时代码编辑和预览功能,简化开发流程。
998 38
Gemini Coder:基于 Google Gemini API 的开源 Web 应用生成工具,支持实时编辑和预览
|
10月前
|
人工智能 运维 安全
网络安全公司推荐:F5荣膺IDC全球Web应用与API防护领导者
网络安全公司推荐:F5荣膺IDC全球Web应用与API防护领导者
277 4
|
11月前
|
XML JSON API
Understanding RESTful API and Web Services: Key Differences and Use Cases
在现代软件开发中,RESTful API和Web服务均用于实现系统间通信,但各有特点。RESTful API遵循REST原则,主要使用HTTP/HTTPS协议,数据格式多为JSON或XML,适用于无状态通信;而Web服务包括SOAP和REST,常用于基于网络的API,采用标准化方法如WSDL或OpenAPI。理解两者区别有助于选择适合应用需求的解决方案,构建高效、可扩展的应用程序。
|
11月前
|
机器学习/深度学习 开发框架 API
Python 高级编程与实战:深入理解 Web 开发与 API 设计
在前几篇文章中,我们探讨了 Python 的基础语法、面向对象编程、函数式编程、元编程、性能优化、调试技巧以及数据科学和机器学习。本文将深入探讨 Python 在 Web 开发和 API 设计中的应用,并通过实战项目帮助你掌握这些技术。
|
Kubernetes 安全 Devops
有效抵御网络应用及API威胁,聊聊F5 BIG-IP Next Web应用防火墙
有效抵御网络应用及API威胁,聊聊F5 BIG-IP Next Web应用防火墙
316 10
有效抵御网络应用及API威胁,聊聊F5 BIG-IP Next Web应用防火墙
|
前端开发 API 开发者
Python Web开发者必看!AJAX、Fetch API实战技巧,让前后端交互如丝般顺滑!
在Web开发中,前后端的高效交互是提升用户体验的关键。本文通过一个基于Flask框架的博客系统实战案例,详细介绍了如何使用AJAX和Fetch API实现不刷新页面查看评论的功能。从后端路由设置到前端请求处理,全面展示了这两种技术的应用技巧,帮助Python Web开发者提升项目质量和开发效率。
333 1
|
JSON API 数据格式
如何使用Python和Flask构建一个简单的RESTful API。Flask是一个轻量级的Web框架
本文介绍了如何使用Python和Flask构建一个简单的RESTful API。Flask是一个轻量级的Web框架,适合小型项目和微服务。文章从环境准备、创建基本Flask应用、定义资源和路由、请求和响应处理、错误处理等方面进行了详细说明,并提供了示例代码。通过这些步骤,读者可以快速上手构建自己的RESTful API。
717 2