From f8a55ca2b6d82464c53dccbf01e75971ecdff5c0 Mon Sep 17 00:00:00 2001 From: taoqf Date: Thu, 29 Nov 2018 13:48:15 +0800 Subject: [PATCH] add definition baidu-app --- types/baidu-app/baidu-app-tests.ts | 2007 ++++++++++++ types/baidu-app/index.d.ts | 4758 ++++++++++++++++++++++++++++ types/baidu-app/tsconfig.json | 24 + types/baidu-app/tslint.json | 7 + 4 files changed, 6796 insertions(+) create mode 100644 types/baidu-app/baidu-app-tests.ts create mode 100644 types/baidu-app/index.d.ts create mode 100644 types/baidu-app/tsconfig.json create mode 100644 types/baidu-app/tslint.json diff --git a/types/baidu-app/baidu-app-tests.ts b/types/baidu-app/baidu-app-tests.ts new file mode 100644 index 0000000000..9987a650ee --- /dev/null +++ b/types/baidu-app/baidu-app-tests.ts @@ -0,0 +1,2007 @@ +(() => { + swan.request({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + method: 'GET', + dataType: 'json', + data: { + key: 'value' + }, + header: { + 'content-type': 'application/json' // 默认值 + }, + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + const requestTask = swan.request({ + url: 'test.php', // 仅为示例,并非真实的接口地址 + data: { + x: '', + y: '' + }, + header: { + 'content-type': 'application/json' + }, + success(res) { + console.log(res.data); + } + }); + // 取消请求任务 + requestTask.abort(); +})(); + +(() => { + swan.chooseImage({ + success(res) { + swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + filePath: res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); +})(); + +(() => { + const uploadTask = swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 开发者服务器 url + filePath: '', // res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + uploadTask.onProgressUpdate(res => { + console.log('上传进度', res.progress); + console.log('已经上传的数据长度', res.totalBytesSent); + console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend); + }); + + uploadTask.abort(); // 取消上传任务 +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + // 下载成功 + if (res.statusCode === 200) { + console.log("临时文件路径" + res.tempFilePath); + } + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const downloadTask = swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + console.log(res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + downloadTask.onProgressUpdate(res => { + console.log('下载进度', res.progress); + console.log('已经下载的数据长度', res.totalBytesWritten); + console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite); + }); + + downloadTask.abort(); // 取消下载任务 +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen((res) => { + console.log('WebSocket连接已打开!', res.header); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' // 仅为示例,并非真实的服务地址 + }); + swan.onSocketError((res) => { + console.log('WebSocket连接打开失败,请检查!'); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); + swan.onSocketMessage((res) => { + console.log('收到服务器内容:', res.data); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com', + success(res) { + swan.closeSocket(); + } + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + + swan.onSocketClose((res) => { + console.log('WebSocket 已关闭!'); + }); + + swan.onSocketOpen(() => { + swan.closeSocket(); + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrIdCard({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrBankCard({ + image, + success(res) { + console.log(res.result.bank_name); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrDrivingLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrVehicleLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); +})(); + +(() => { + swan.ai.textReview({ + content: '', + success(res) { + console.log(res.result.spam); // 0 表示审核通过 + } + }); +})(); + +(() => { + swan.ai.textToAudio({ + ctp: '1', + lan: 'zh', + tex: '这是一段测试文字', + success(res) { + console.log(res.filePath); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.imageAudit({ + image, + success(res) { + console.log(res.conclusionType); // 1 为合规 + } + }); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.advancedGeneralIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.objectDetectIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.carClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.dishClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.logoClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.animalClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.plantClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); +})(); + +(() => { + const voiceRecognizer = swan.ai.getVoiceRecognizer(); + + voiceRecognizer.onStart(() => { + console.log('voice start'); + }); + voiceRecognizer.onRecognize(res => { + console.log('voice recognize', res); + }); + voiceRecognizer.onFinish(res => { + console.log('voice end', res); + }); + voiceRecognizer.onError(err => { + console.log('voice error', err); + }); + + const options = { + mode: 'dnn', + longSpeech: false + }; + + voiceRecognizer.start(options); +})(); + +(() => { + swan.chooseImage({ + count: 1, + sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 + sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 + success(res) { + // 成功则返回图片的本地文件路径列表 tempFilePaths + console.log(res.tempFilePaths); + // 文件列表对象 + console.log(res.tempFiles); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.previewImage({ + current: '', // 当前显示图片的http链接 + urls: [], // 需要预览的图片http链接列表 + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + swan.getImageInfo({ + src: '/xxx/xxx.jpg', + success(res) { + // 成功则返回图片高,宽,本地路径 + console.log(res.width); + console.log(res.height); + console.log(res.path); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.saveImageToPhotosAlbum({ + filePath: '/xxx/xxx.jpg', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const recorderManager = swan.getRecorderManager(); + + recorderManager.onStart(() => { + // 开始录音事件 + console.log('recorder start'); + }); + recorderManager.onPause(() => { + // 暂停录音事件 + console.log('recorder pause'); + }); + recorderManager.onStop((res) => { + // 停止录音事件 + console.log('recorder stop', res); + const { tempFilePath } = res; + }); + + const options = { + duration: 10000, + sampleRate: 44100, + numberOfChannels: 1, + encodeBitRate: 96000, + format: 'aac' + }; + + recorderManager.start(options); +})(); + +(() => { + const backgroundAudioManager = swan.getBackgroundAudioManager(); + + backgroundAudioManager.title = '此时此刻'; + backgroundAudioManager.epname = '此时此刻'; + backgroundAudioManager.singer = '许巍'; + backgroundAudioManager.coverImgUrl = 'xxx'; + backgroundAudioManager.src = 'xxx'; +})(); + +(() => { + const innerAudioContext = swan.createInnerAudioContext(); + innerAudioContext.src = 'xxx'; + innerAudioContext.autoplay = true; + innerAudioContext.seek({ + position: 10 + }); + innerAudioContext.onPlay((res) => { + console.log('开始播放'); + }); +})(); + +(() => { + Page({ + data: { + sourceType: ['album', 'camera'], + compressed: false, + maxDuration: 60, + src: '' + }, + + chooseVideo() { + const self = this; + swan.chooseVideo({ + sourceType: this.getData('sourceType'), + compressed: this.getData('compressed'), + maxDuration: this.getData('maxDuration'), + success(res) { + // 成功返回选定视频的临时文件路径 + self.setData('src', res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); + swan.saveVideoToPhotosAlbum({ + filePath: 'bdfile://xxx', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const myVideo = swan.createVideoContext('myVideo'); + myVideo.play(); +})(); + +(() => { + swan.chooseImage({ + count: 1, + success(res) { + const tempFilePaths = res.tempFilePaths; + swan.saveFile({ + tempFilePath: tempFilePaths[0], + success(res) { + const savedFilePath = res.savedFilePath; + } + }); + } + }); + swan.getFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.digest); + } + }); + swan.getSavedFileList({ + success(res) { + const fileList = res.fileList; + } + }); + swan.getSavedFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.createTime); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getSavedFileList({ + success(res) { + if (res.fileList.length > 0) { + swan.removeSavedFile({ + filePath: res.fileList[0].filePath, + success(res) { + console.log(res.filePath); + } + }); + } + } + }); +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx.pdf', + success(res) { + const filePath = res.tempFilePath; + swan.openDocument({ + filePath, + success(res) { + console.log('打开文档成功'); + } + }); + } + }); +})(); + +(() => { + swan.setStorage({ + key: 'key', + data: 'value' + }); +})(); + +(() => { + try { + swan.setStorageSync('key', 'value'); + } catch (e) { + } + swan.getStorage({ + key: 'key', + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageSync('key'); + } catch (e) { + } + swan.getStorageInfo({ + success(res) { + console.log(res.keys); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageInfoSync(); + console.log(result); + } catch (e) { + } +})(); + +(() => { + swan.removeStorage({ + key: 'key', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + swan.removeStorageSync('key'); + } catch (e) { + } + try { + swan.clearStorageSync(); + } catch (e) { + } +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + console.log('纬度:' + res.latitude); + console.log('经度:' + res.longitude); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + swan.openLocation({ + latitude: res.latitude, + longitude: res.longitude, + scale: 18 + }); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + let mapContext: swan.MapContext; + Page({ + data: { + latitude: '40.042500', + longitude: '116.274040', + }, + onReady() { + mapContext = swan.createMapContext('myMap'); + }, + getCenterLocation() { + mapContext.getCenterLocation({ + success(res) { + console.log("经度" + res.longitude); + console.log("纬度" + res.latitude); + } + }); + }, + moveToLocation() { + mapContext.moveToLocation(); + }, + translateMarker() { + mapContext.translateMarker({ + markerId: 0, + rotate: 90, + autoRotate: true, + duration: 1000, + destination: { + latitude: 23.10229, + longitude: 113.3345211, + }, + animationEnd() { + console.log('animation end'); + } + }); + }, + includePoints() { + mapContext.includePoints({ + padding: [10], + points: [{ + latitude: 23, + longitude: 113.33, + }, { + latitude: 23, + longitude: 113.3345211, + }] + }); + }, + getRegion() { + mapContext.getRegion({ + success(res) { + console.log("西南角的经纬度" + res.southwest); + console.log("东北角的经纬度" + res.northeast); + } + }); + } + }); +})(); + +(() => { + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + ctx.draw(); + } + }); + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + } + }); + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + + ctx.draw(); + + swan.canvasGetImageData({ + canvasId: 'myCanvas', + x: 0, + y: 0, + width: 100, + height: 100, + success(res) { + console.log(res); + } + }); + const data = new Uint8ClampedArray([255, 0, 0, 1]); + swan.canvasPutImageData({ + canvasId: 'myCanvas', + data, + x: 0, + y: 0, + width: 1, + height: 2, + success(res) { + console.log('success'); + } + }); + swan.canvasToTempFilePath({ + x: 100, + y: 200, + width: 50, + height: 50, + destWidth: 100, + destHeight: 100, + canvasId: 'myCanvas', + success(res) { + console.log(res.tempFilePath); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.setShadow(10, 50, 50, 'red'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create linear gradient + const grd = ctx.createLinearGradient(0, 0, 200, 0); + grd.addColorStop(0, 'blue'); + grd.addColorStop(1, 'red'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createCircularGradient(75, 50, 50); + grd.addColorStop(0, 'red'); + grd.addColorStop(1, 'blue'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createLinearGradient(30, 10, 120, 10); + grd.addColorStop(0, 'red'); + grd.addColorStop(0.16, 'orange'); + grd.addColorStop(0.33, 'yellow'); + grd.addColorStop(0.5, 'green'); + grd.addColorStop(0.66, 'cyan'); + grd.addColorStop(0.83, 'blue'); + grd.addColorStop(1, 'purple'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(5); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('butt'); + ctx.setLineWidth(10); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('round'); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('square'); + ctx.setLineWidth(10); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('bevel'); + ctx.setLineWidth(10); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('round'); + ctx.setLineWidth(10); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('miter'); + ctx.setLineWidth(10); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setLineDash([10, 20], 5); + ctx.beginPath(); + ctx.moveTo(0, 100); + ctx.lineTo(400, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(1); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(2); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(3); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(4); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(30, 30, 150, 75); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setStrokeStyle('blue'); + ctx.strokeRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('red'); + ctx.fillRect(0, 0, 150, 200); + ctx.setFillStyle('blue'); + ctx.fillRect(150, 0, 150, 200); + ctx.clearRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(10, 10, 100, 30); + ctx.setFillStyle('red'); + ctx.fill(); + ctx.beginPath(); + ctx.rect(10, 40, 100, 30); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 70, 100, 30); + ctx.rect(10, 100, 100, 30); + ctx.setFillStyle('green'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.closePath(); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.lineTo(100, 10); + ctx.moveTo(10, 100); + ctx.lineTo(100, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.rect(10, 10, 100, 50); + ctx.lineTo(110, 60); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.arc(100, 75, 50, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.downloadFile({ + url: 'https://b.bdstatic.com/searchbox/icms/searchbox/img/LOGO300x300.jpg', + success(res) { + ctx.save(); + ctx.beginPath(); + ctx.arc(50, 50, 25, 0, 2 * Math.PI); + ctx.clip(); + ctx.drawImage(res.tempFilePath, 25, 25); + ctx.restore(); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('20', 20, 20); + ctx.setFontSize(30); + ctx.fillText('30', 40, 40); + ctx.setFontSize(40); + ctx.fillText('40', 60, 60); + ctx.setFontSize(50); + ctx.fillText('50', 90, 90); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('Hello', 20, 20); + ctx.fillText('World', 100, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(150, 20); + ctx.lineTo(150, 170); + ctx.stroke(); + + ctx.setFontSize(15); + ctx.setTextAlign('left'); + ctx.fillText('textAlign=left', 150, 60); + + ctx.setTextAlign('center'); + ctx.fillText('textAlign=center', 150, 80); + + ctx.setTextAlign('right'); + ctx.fillText('textAlign=right', 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(5, 75); + ctx.lineTo(295, 75); + ctx.stroke(); + + ctx.setFontSize(20); + + ctx.setTextBaseline('top'); + ctx.fillText('top', 5, 75); + + ctx.setTextBaseline('middle'); + ctx.fillText('middle', 50, 75); + + ctx.setTextBaseline('bottom'); + ctx.fillText('bottom', 120, 75); + + ctx.setTextBaseline('normal'); + ctx.fillText('normal', 200, 75); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.chooseImage({ + success(res) { + ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFillStyle('red'); + ctx.fillRect(10, 10, 150, 100); + ctx.setGlobalAlpha(0.2); + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 150, 100); + ctx.setFillStyle('yellow'); + ctx.fillRect(100, 100, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.font = 'italic bold 20px cursive'; + const metrics = ctx.measureText('Hello World'); + console.log(metrics.width); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + const pattern = ctx.createPattern('/path/to/image', 'repeat-x'); + ctx.fillStyle = pattern; + ctx.fillRect(0, 0, 300, 150); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.bezierCurveTo(20, 100, 200, 100, 200, 20); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.quadraticCurveTo(20, 100, 200, 20); + ctx.setStrokeStyle('blue'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + ctx.draw(); + ctx.fillRect(30, 30, 150, 100); + ctx.draw(); +})(); + +(() => { + swan.showToast({ + title: '我是标题', + icon: 'loading', + duration: 1000, + }); + swan.showLoading({ + title: '加载中', + mask: 'true' + }); + + setTimeout(() => { + swan.hideLoading(); + }, 2000); + + swan.showModal({ + title: '提示', + content: '这是一个模态弹窗', + cancelColor: '#999999', + confirmColor: '#0099cc', + success(res) { + if (res.confirm) { + console.log('用户点击了确定'); + } else if (res.cancel) { + console.log('用户点击了取消'); + } + } + }); + swan.showActionSheet({ + itemList: ['同意', '一般', '不同意'], + success(res) { + console.log(`用户点击了第${(res.tapIndex + 1)}个按钮`); + } + }); +})(); + +(() => { + swan.setNavigationBarTitle({ + title: '我是页面标题' + }); + swan.setNavigationBarColor({ + frontColor: '#ffffff', + backgroundColor: '#ff0000', + animation: { + duration: 500, + timingFunc: 'linear' + } + }); +})(); + +(() => { + swan.setTabBarBadge({ + index: 0, + text: '文本' + }); + swan.removeTabBarBadge({ + index: 0 + }); + swan.showTabBarRedDot({ + index: 0 + }); + swan.hideTabBarRedDot({ + index: 0 + }); + swan.setTabBarStyle({ + color: '#FFFFBD', + selectedColor: '#FFFFBD', + backgroundColor: '#FFFFBD', + borderStyle: 'white' + }); + swan.setTabBarItem({ + index: 0, + text: '文本', + // 图片路径 + iconPath: '/images/component_normal.png', + // 选中图片路径 + selectedIconPath: '/images/component_selected.png', + }); + swan.showTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.hideTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.navigateTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.redirectTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.switchTab({ + url: '/list', + }); + // 注意:调用 navigateTo 跳转时,调用页面会被加入堆栈,而 redirectTo 方法则不会。见下方示例代码 + + // 当前是首页 + swan.navigateTo({ + url: 'list?key=value' + }); + + // 当前是列表页 + swan.navigateTo({ + url: 'detail?key=value' + }); + + // 在详情页内 navigateBack,将返回首页 + swan.navigateBack({ + delta: 2 + }); + swan.reLaunch({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); +})(); + +(() => { + const animation = swan.createAnimation({ + transformOrigin: "50% 50%", + duration: 1000, + timingFunction: "ease", + delay: 0 + }); + Page({ + data: { + animationData: {} + }, + starttoanimate() { + const animation = swan.createAnimation(); + animation.rotate(90).translateY(10).step(); + animation.rotate(-90).translateY(-10).step(); + this.setData({ + animationData: animation.export() + }); + } + }); +})(); + +(() => { + swan.pageScrollTo({ + scrollTop: 0, + duration: 300 + }); +})(); + +(() => { + Page({ + onPullDownRefresh() { + // do something + } + }); + swan.startPullDownRefresh(); + swan.stopPullDownRefresh(); +})(); + +(() => { + swan.createIntersectionObserver({} as any, { + selectAll: true + }).relativeTo('.container') + .observe('.ball', res => { + console.log(res.intersectionRect); // 相交区域 + console.log(res.intersectionRect.left); // 相交区域的左边界坐标 + console.log(res.intersectionRect.top); // 相交区域的上边界坐标 + console.log(res.intersectionRect.width); // 相交区域的宽度 + console.log(res.intersectionRect.height); // 相交区域的高度 + }); + Page({ + queryMultipleNodes() { + const query = swan.createSelectorQuery(); + query.select('#the-id').boundingClientRect(); + query.selectViewport().scrollOffset(); + query.exec((res) => { + // res[0].top, // #the-id节点的上边界坐标 + // res[1].scrollTop // 显示区域的竖直滚动位置 + }); + } + }); + Component({ + // queryMultipleNodes() { + // const query = swan.createSelectorQuery().in(this); + // query.select('#the-id').boundingClientRect((res) => { + // // res.top // 这个组件内 #the-id 节点的上边界坐标 + // }).exec(); + // } + }); + Page({ + getRect() { + swan.createSelectorQuery().select('#the-id').boundingClientRect((res) => { + const rect = res as swan.NodesRefRect; + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }).exec(); + }, + getAllRects() { + swan.createSelectorQuery().selectAll('.a-class').boundingClientRect((rects) => { + (rects as swan.NodesRefRect[]).forEach((rect) => { + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }); + }).exec(); + } + }); + Page({ + getScrollOffset() { + swan.createSelectorQuery().selectViewport().scrollOffset((res) => { + res.id; // 节点的ID + res.dataset; // 节点的dataset + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + }).exec(); + } + }); + Page({ + getFields() { + swan.createSelectorQuery().select('#the-id').fields({ + dataset: true, + size: true, + scrollOffset: true, + properties: ['scrollX', 'scrollY'], + computedStyle: ['margin', 'backgroundColor'] + }, (res) => { + res.dataset; // 节点的dataset + res.width; // 节点的宽度 + res.height; // 节点的高度 + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + res.scrollX; // 节点 scroll-x 属性的当前值 + res.scrollY; // 节点 scroll-y 属性的当前值 + // 此处返回指定要返回的样式名 + res.margin; + res.backgroundColor; + }).exec(); + } + }); +})(); + +(() => { + swan.getSystemInfo({ + success(res) { + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } + }); + try { + const res = swan.getSystemInfoSync(); + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } catch (e) { + // Do something when catch error + } + try { + const res = swan.getEnvInfoSync(); + console.log(res.appKey); + console.log(res.appName); + console.log(res.lastAppURL); + console.log(res.sdkVersion); + console.log(res.scheme); + } catch (e) { + // Do something when catch error + } + swan.canIUse('view.hover-class'); + swan.canIUse('scroll-view.scroll-x'); + swan.canIUse('cover-view'); + swan.canIUse('button.size.default'); + swan.canIUse('button.size.default'); + swan.canIUse('request.object.success.data'); + swan.canIUse('getSavedFileList'); + swan.canIUse('getSavedFileList.object'); + swan.canIUse('getSavedFileList.object.success'); +})(); + +(() => { + swan.onMemoryWarning((res) => { + console.log('onMemoryWarningReceive'); + }); +})(); + +(() => { + swan.getNetworkType({ + success(res) { + console.log(res.networkType); + } + }); + swan.onNetworkStatusChange((res) => { + console.log(res.isConnected); + console.log(res.networkType); + }); +})(); + +(() => { + swan.onAccelerometerChange((res) => { + console.log(res.x); + console.log(res.y); + console.log(res.z); + }); + swan.startAccelerometer({ + interval: 'ui' + }); + swan.stopAccelerometer(); +})(); + +(() => { + swan.onCompassChange((res) => { + console.log(res.direction); + }); + swan.startCompass(); + swan.stopCompass(); +})(); + +(() => { + swan.scanCode({ + success(res) { + console.log(res.result); + console.log(res.scanType); + } + }); +})(); + +(() => { + swan.onUserCaptureScreen(() => { + console.log('用户截屏了'); + }); +})(); + +(() => { + swan.makePhoneCall({ + phoneNumber: '000000' // 仅为示例,并非真实的电话号码 + }); +})(); + +(() => { + swan.setClipboardData({ + data: 'baidu', + success(res) { + swan.getClipboardData({ + success(res) { + console.log(res.data); // baidu + } + }); + } + }); + swan.getClipboardData({ + success(res) { + console.log(res.data); + } + }); +})(); + +(() => { + swan.getExtConfig({ + success(res) { + console.log(res.extConfig); + } + }); + const data = swan.getExtConfigSync(); + console.log(data.extConfig); +})(); + +(() => { + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址 + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('login fail', err); + } + }); + swan.checkSession({ + success(res) { + console.log('登录态有效'); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + swan.request({ + url: "https://xxx/decrypt_user_data", // 开发者服务器地址,对 data 进行解密 + data: { + data: res.data, + iv: res.iv + } + }); + } + }); + }, + fail(err) { + console.log('登录态无效'); + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址,用 code 换取 session_key + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('登录失败', err); + } + }); + } + }); + + try { + const result = swan.isLoginSync(); + console.log('isLoginSync', result); + } catch (e) { + console.log('error', e); + } +})(); + +(() => { + swan.authorize({ + scope: 'scope.userLocation', + success(res) { + // 用户已经同意智能小程序使用定位功能 + swan.getLocation(); + } + }); +})(); + +(() => { + swan.getSwanId({ + success(res) { + console.log(res.data.swanid); + } + }); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + } + }); +})(); + +(() => { + swan.openSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); + swan.getSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); +})(); + +(() => { + Page({ + onShareAppMessage() { + return { + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }; + } + }); + swan.openShare({ + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }); +})(); + +(() => { + swan.chooseAddress({ + success(res) { + console.log(res.userName); + console.log(res.postalCode); + console.log(res.provinceName); + console.log(res.cityName); + console.log(res.countyName); + console.log(res.detailInfo); + console.log(res.telNumber); + } + }); +})(); + +(() => { + swan.requestPolymerPayment({ + orderInfo: { + dealId: "470193086", + appKey: "MMMabc", + totalAmount: "1", + tpOrderId: "3028903626", + dealTitle: "智能小程序Demo支付测试", + signFieldsRange: 1, + rsaSign: '', + bizInfo: '' + }, + success(res) { + swan.showToast({ + title: '支付成功', + icon: 'success' + }); + }, + fail(err) { + swan.showToast({ + title: JSON.stringify(err) + }); + console.log('pay fail', err); + } + }); +})(); + +(() => { + swan.chooseInvoiceTitle({ + success(res) { + console.log(res.type); + console.log(res.title); + console.log(res.taxNumber); + console.log(res.companyAddress); + console.log(res.telephone); + console.log(res.bankName); + console.log(res.bankAccount); + } + }); +})(); + +(() => { + swan.navigateToSmartProgram({ + appKey: '4fecoAqgCIUtzIyA4FAPgoyrc4oUc25c', // 要打开的小程序 App Key + path: '', // 打开的页面路径,如果为空则打开首页 + extraData: { + foo: 'baidu' + }, + success(res) { + // 打开成功 + } + }); + swan.navigateBackSmartProgram({ + extraData: { + foo: 'baidu' + }, + success(res) { + // 返回成功 + } + }); +})(); + +(() => { + if (swan.setMetaDescription) { + swan.setMetaDescription({ + content: '当前小程序页面描述信息', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setMetaKeywords) { + swan.setMetaKeywords({ + content: '小程序, 关键字', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setDocumentTitle) { + swan.setDocumentTitle({ + title: '我是页面标题' + }); + } +})(); + +(() => { + swan.loadSubPackage({ + root: 'subpackage', + success(res) { + console.log('下载成功', res); + }, + fail(err) { + console.log('下载失败', err); + } + }); +})(); + +(() => { + const updateManager = swan.getUpdateManager(); + + updateManager.onCheckForUpdate((res) => { + // 请求完新版本信息的回调 + console.log(res.hasUpdate); + }); + + updateManager.onUpdateReady((res) => { + swan.showModal({ + title: '更新提示', + content: '新版本已经准备好,是否重启应用?', + success(res) { + if (res.confirm) { + // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 + updateManager.applyUpdate(); + } + } + }); + }); + + updateManager.onUpdateFailed((res) => { + // 新的版本下载失败 + }); +})(); + +(() => { + // 打开调试 + swan.setEnableDebug({ + enableDebug: true + }); + + // 关闭调试 + swan.setEnableDebug({ + enableDebug: false + }); +})(); + +(() => { + swan.reportAnalytics('purchase', { + price: 120, + color: 'red' + }); +})(); diff --git a/types/baidu-app/index.d.ts b/types/baidu-app/index.d.ts new file mode 100644 index 0000000000..244e9dd473 --- /dev/null +++ b/types/baidu-app/index.d.ts @@ -0,0 +1,4758 @@ +// Type definitions for swan-app 2.2 +// Project: https://smartprogram.baidu.com/docs/develop/tutorial/codedir/ +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.8 + +declare namespace swan { + // #region 基本参数 + interface DataResponse { + /** 回调函数返回的内容 */ + data: string | ArrayBuffer; + statusCode: number; + header: any; + result: string; + } + interface ErrMsgResponse { + /** 成功:ok,错误:详细信息 */ + errMsg: "ok" | string; + } + interface TempFileResponse { + /** 文件的临时路径 */ + tempFilePath: string; + /** 开发者服务器返回的 HTTP 状态码 */ + statusCode: number; + } + interface BaseOptions { + /** 接口调用成功的回调函数 */ + success?(res: R): void; + /** 接口调用失败的回调函数 */ + fail?(res: E): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(res: any): void; + } + interface ErrCodeResponse { + errCode: number; + } + // #endregion + // #region 网络API列表 + // 发起请求 + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions extends BaseOptions { + /** 开发者服务器接口地址 */ + url: string; + /** 请求的参数 */ + data?: string | object; + /** 设置请求的 header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: + | "GET" + | "OPTIONS" + | "GET" + | "HEAD" + | "POST" + | "PUT" + | "DELETE"; + /** 如果设为json,会尝试对返回的数据做一次 JSON.parse 默认值为json */ + dataType?: string; + /** + * 设置响应的数据类型。合法值:text、arraybuffer 默认值为text + * @version 1.7.0 + */ + responseType?: string; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?(res: DataResponse): void; + fail?(err: { errCode: number; errMsg: string; }): void; + } + /** + * swan.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 + */ + function request(options: RequestOptions): RequestTask; + + /** + * 返回一个 requestTask 对象,通过 requestTask,可中断请求任务。 + */ + interface RequestTask { + abort(): void; + } + + interface UploadTask { + /** + * 监听上传进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 上传进度百分比 */ + progress: number; + /** 已经上传的数据长度,单位 Bytes */ + totalBytesSent: number; + /** 预期需要上传的数据总长度,单位 Bytes */ + totalBytesExpectedToSend: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + // 上传下载 + interface UploadFileOptions extends BaseOptions { + /** 开发者服务器 url */ + url: string; + /** 要上传文件资源的路径 */ + filePath: string; + /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + name: string; + /** HTTP 请求 Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form data */ + formData?: any; + } + interface UploadFileResponse { + data: string; // 开发者服务器返回的数据 + statusCode: number; // 开发者服务器返回的 HTTP 状态码 + } + /** + * 将本地资源上传到开发者服务器。 + * 如页面通过 swan.chooseImage 等接口获取到一个本地资源的临时文件路径后, + * 可通过此接口将本地资源上传到指定服务器。 + * 客户端发起一个 HTTPS POST 请求, + * 其中 Content-Type 为 multipart/form-data 。 + */ + function uploadFile(options: UploadFileOptions): UploadTask; + interface DownloadTask { + /** + * 监听下载进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 下载进度百分比 */ + progress: number; + /** 已经下载的数据长度,单位 Bytes */ + totalBytesWritten: number; + /** 预期需要下载的数据总长度,单位 Bytes */ + totalBytesExpectedToWrite: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + interface DownloadFileOptions extends BaseOptions { + /** 下载资源的 url */ + url: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, + * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 + */ + function downloadFile(options: DownloadFileOptions): DownloadTask; + // WebSocket + interface ConnectSocketOptions extends BaseOptions { + /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ + url: string; + /** HTTP Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: string; + /** + * 子协议数组 + * @version 1.4.0 + */ + protocols?: string[]; + } + /** + * 创建一个 WebSocket 连接; + * 一个微信小程序同时只能有一个 WebSocket 连接, + * 如果当前已存在一个 WebSocket 连接, + * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + /** 监听WebSocket连接打开事件。 */ + function onSocketOpen(callback: (res: any) => void): void; + /** 监听WebSocket错误。 */ + function onSocketError(callback: (error: any) => void): void; + interface SendSocketMessageOptions extends BaseOptions { + /** 需要发送的内容 */ + data: string | ArrayBuffer; + } + /** + * 通过 WebSocket 连接发送数据,需要先 swan.connectSocket, + * 并在 swan.onSocketOpen 回调之后才能发送。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: (res: DataResponse) => void): void; + /** + * 关闭WebSocket连接。 + */ + interface CloseSocketOptions extends BaseOptions { + code?: number; // 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) 1.4.0 + reason?: string; // 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) + } + + /** + * 关闭WebSocket连接。 + */ + function closeSocket(options?: CloseSocketOptions): void; + /** 监听WebSocket关闭。 */ + function onSocketClose(callback: (res: any) => void): void; + /** + * 在接入AI之前需要使用管理员权限操作详细情况官网 + * https://smartprogram.baidu.com/docs/develop/api/ai/ + */ + // #region AI + namespace ai { + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + interface ocrIdCardOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false: 不检测旋转角度,默认不检测。 + id_card_side?: string; // front:身份证含照片的一面;back:身份证带国徽的一面。 + detect_risk?: boolean; // 是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能,默认不开启,即:false。可选值:true-开启;false-不开启。 + success?(res: ocrIdCardResponse): void; + } + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + interface ocrBankCardOptions extends BaseOptions { + image: string; // 图片资源地址 + success?(res: ocrBankCardResponse): void; + } + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + interface ocrDrivingLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true;false:不检测旋转角度,默认不检测。 + unified_valid_period?: boolean; // true: 归一化格式输出;false 或无此参数按非归一化格式输出。 + success?(res: ocrDrivingLicenseResponse): void; + } + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + interface ocrVehicleLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false:不检测旋转角度,默认不检测。 + accuracy?: string; // normal 使用快速服务,1200ms左右时延;缺省或其它值使用高精度服务,1600ms左右时延。 + success?(res: ocrVehicleLicenseResponse): void; + } + interface ocrIdCardResponse { + direction: number; // 图像方向,当 detect_direction=true 时存在。-1: 未定义,0: 正向,1: 逆时针90度,2: 逆时针180度,3: 逆时针270度。 + image_status: string; // normal-识别正常;reversed_side-身份证正反面颠倒;non_idcard-上传的图片中不包含身份证;blurred-身份证模糊;other_type_card-其他类型证照;over_exposure-身份证关键字段反光或过曝;unknown-未知状态。 + risk_type: string; // 输入参数 detect_risk = true 时,则返回该字段识别身份证类型: normal-正常身份证;copy-复印件;temporary-临时身份证;screen-翻拍;unknown-其他未知情况。 + edit_tool: string; // 如果参数 detect_risk = true 时,则返回此字段。如果检测身份证被编辑过,该字段指定编辑软件名称,如:Adobe Photoshop CC 2014 (Macintosh),如果没有被编辑过则返回值无此参数。 + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示words_result的元素个数。 + words_result: { // 定位和识别结果 + [key: string]: { + location: { // 位置数组(坐标0点为左上角) + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高。 + } + words: string; // 识别结果字符串 + } + }; + } + interface ocrBankCardResponse { + log_id: string; // 请求标识码,随机数,唯一。 + result: { // 返回结果 + bank_card_number: string; // 银行卡卡号 + bank_name: string; // 银行名,不能识别时为空 。 + bank_card_type: string; // 银行卡类型,0: 不能识别; 1: 借记卡; 2: 信用卡 。 + }; + } + interface ocrDrivingLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + interface ocrVehicleLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + function ocrIdCard(options: ocrIdCardOptions): void; + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + function ocrBankCard(options: ocrBankCardOptions): void; + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + function ocrDrivingLicense(options: ocrDrivingLicenseOptions): void; + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + function ocrVehicleLicense(options: ocrVehicleLicenseOptions): void; + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + interface textReviewOptions extends BaseOptions { + content: string; // 待审核文本,UTF-8,不可为空,不超过20000字节。 + success?(res: textReviewResponse): void; + } + interface textReviewResponse { + log_id: string; // 唯一的log id,用于问题定位。 + result: { // 审核结果详情 + spam: number; // 请求中是否包含违禁,0表示非违禁,1表示违禁,2表示建议人工复审 。 + reject: any[]; // 审核未通过的类别列表与详情 + review: any[]; // 待人工复审的类别列表与详情 + pass: Array<{ // 审核通过的类别列表与详情 + label: number; // 请求中的违禁类型 + score: number; // 违禁检测分,范围 0~1,数值从低到高代表风险程度的高低 。 + hit: string[]; // 违禁类型对应命中的违禁词集合,可能为空 。 + }>; + }; + /** + * 违禁labels类型说明: + * 值 说明 + * 1 暴恐违禁 + * 2 文本色情 + * 3 政治敏感 + * 4 恶意推广 + * 5 低俗辱骂 + */ + } + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + function textReview(options: textReviewOptions): void; + /** + * 将文本转换为可以播放的mp3文件。 + */ + interface textToAudioOptions extends BaseOptions { + tex: string; // 合成的文本,使用UTF-8编码,小于512个中文字或者英文数字(文本在百度服务器内转换为GBK后,长度必须小于1024字节)。 + ctp?: string | number; // 客户端类型选择,Web端填写固定值1。 + lan?: string; // 固定值zh。语言选择,目前只有中英文混合模式,填写固定值zh。 + spd?: string; // 语速,取值0-9,默认为5中语速。 + pit?: string; // 音调,取值0-9,默认为5中语调。 + vol?: string; // 音量,取值0-9,默认为5中音量。 + per?: string; // 发音人选择, 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声。 + success?(res: textToAudioResponse): void; + } + interface textToAudioResponse { + filePath: string; + } + /** + * 将文本转换为可以播放的mp3文件。 + */ + function textToAudio(options: textToAudioOptions): void; + /** + * 自定义图像审核。 + */ + interface imageAuditOptions extends BaseOptions { + image: string; // 图像资源地址 + imgUrl?: string; // 网图URL地址,以网图形式请求,图片Url需要做UrlEncode,不能与image并存。 + success?(res: imageAuditResponse): void; + } + interface imageAuditResponse { + log_id: string; // 请求唯一id + conclusion: string; // 审核结果描述,成功才返回,失败不返回。 + conclusionType: number; // 审核结果标识,成功才返回,失败不返回。 + data: imageAuditdata[]; + // 审核项详细信息,响应成功并且conclusion为疑似或不合规时才返回,响应失败或conclusion为合规是不返回。 + } + interface imageAuditdata { + type: number; + msg: number; + probability: number; + stars: imageAuditdata[]; + words: number; + } + /** + * 自定义图像审核。 + */ + function imageAudit(options: imageAuditOptions): void; + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + interface GeneralIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: GeneralIdentifyResponse): void; + } + interface GeneralIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 标签结果数组 + keyword: string; // 图片中的物体或场景名称 + score: number; // 置信度,0-1 + root: string; // 识别结果的上层标签,有部分钱币、动漫、烟酒等tag无上层标签。 + }>; + } + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + function advancedGeneralIdentify(options: GeneralIdentifyOptions): void; + /** + * 用户向服务请求检测图像中的主体位置。 + */ + interface DetectIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + with_face?: number; // 如果检测主体是人,主体区域是否带上人脸部分,0-不带人脸区域,其他-带人脸区域,裁剪类需求推荐带人脸,检索/识别类需求推荐不带人脸。默认取1,带人脸。 + success?(res: DetectIdentifyResponse): void; + } + interface DetectIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: { // 裁剪结果 + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高度。 + }; + } + /** + * 用户向服务请求检测图像中的主体位置。 + */ + function objectDetectIdentify(options: DetectIdentifyOptions): void; + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + interface carClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + color_result?: string; // 颜色 + top_num?: number; // 返回结果top n,默认5。 + success?(res: carClassifyResponse): void; + } + interface carClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ + name: string; // 车型名称,示例:宝马x6 + score: number; // 置信度,示例:0.5321 + year: string; // 年份 + }>; + location_result: { // 车在图片中的位置信息 + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; + } + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + function carClassify(options: carClassifyOptions): void; + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + interface dishClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + filter_threshold?: number; // 默认0.95,可以通过该参数调节识别效果,降低非菜识别率. + top_num?: number; // 返回结果top n,默认5。 + success?(res: dishClassifyResponse): void; + } + interface dishClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 菜品识别结果数组 + name: string; // 菜名,示例:鱼香肉丝。 + calorie: number; // 卡路里,每100g的卡路里含量。 + probability: number; // 识别结果中每一行的置信度值,0-1。 + }>; + } + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + function dishClassify(options: dishClassifyOptions): void; + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + interface logoClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + custom_lib?: boolean; // 是否只检索用户子库,true则只检索用户子库,false(默认)为检索底库+用户子库。 + success?(res: logoClassifyResponse): void; + } + interface logoClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + type: number; // type=0 为1千种高优商标识别结果;type=1 为2万类logo库的结果;其它type为自定义logo库结果。 + name: number; // 识别的品牌名称 + probability: number; // 分类结果置信度(0–1.0) + location: { + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; // 位置信息(左起像素位置、上起像素位置、像素宽、像素高) + }>; + } + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + function logoClassify(options: logoClassifyOptions): void; + /** + * 用于检测和识别图片中的动物信息 + */ + interface animalClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + top_num?: number; // 返回预测得分top结果数,默认为6 + success?(res: animalClassifyResponse): void; + } + interface animalClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + name: number; // 动物名称,示例:蒙古马。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的动物信息 + */ + function animalClassify(options: animalClassifyOptions): void; + /** + * 用于检测和识别图片中的植物信息 + */ + interface plantClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: plantClassifyResponse): void; + } + interface plantClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ // 菜品识别结果数组 + name: number; // 植物名称,示例:吉娃莲。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的植物信息 + */ + function plantClassify(options: plantClassifyOptions): void; + + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + interface VoiceRecognizerStart { + mode?: string; // 听音模式,有效值dnn/touch + longSpeech?: boolean; // 是否开启长语音 + context?: string; // 语音识别所用的场景值,有效值见下表格。 + } + interface VoiceRecognizeResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceErrorResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceRecognizerTask { + start(options: VoiceRecognizerStart): void; // 开始; + stop(): void; // 停止; + cancel(): void; // 取消; + onStart(callback: () => void): void; // 引擎准备就绪,可以开始说话; + onRecognize(callback: (res: VoiceRecognizeResponse) => void): void; // ;有识别结果返回 + onFinish(callback: (res: DataResponse) => void): void; // 识别完成; + onError(callback: (res: VoiceErrorResponse) => void): void; // 识别遇到错;误 + } + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + function getVoiceRecognizer(): VoiceRecognizerTask; + } + // #endregion + + // #endregion + // #region 媒体API列表 + // 媒体-----图片 + type ImageSizeType = "original" | "compressed"; + type ImageSourceType = "album" | "camera"; + type VideoSourceType = "album" | "camera"; + type CameraDevice = "front" | "back"; + interface TempFile { + /** 本地文件路径 */ + path: string; + /** 本地文件大小,单位:B */ + size: number; + } + interface TempFilesData { + /** 文件的临时路径 */ + tempFilePaths: string; + /** + * 图片的本地文件列表,每一项是一个 File 对象 + * @version 1.2.0 + */ + tempFiles: TempFile[]; + } + interface ChooseImageOptions extends BaseOptions { + /** 最多可以选择的图片张数,默认9 */ + count?: number; + /** original 原图,compressed 压缩图,默认二者都有 */ + sizeType?: ImageSizeType[]; + /** album 从相册选图,camera 使用相机,默认二者都有 */ + sourceType?: ImageSourceType[]; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success(res: TempFilesData): void; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: ChooseImageOptions): void; + interface PreviewImageOptions extends BaseOptions { + /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ + current?: string; + /** 需要预览的图片链接列表 */ + urls: string[]; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + interface GetImageInfoOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + src: string; + } + /** + * 获取图片信息 + */ + function getImageInfo(options: GetImageInfoOptions): void; + interface SaveImageToPhotosAlbumOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + filePath: string; + success(res: { errMsg: string }): void; + } + /** + * 保存图片到系统相册。 + * 需要用户授权 scope.writePhotosAlbum + * @version 1.2.0 + */ + function saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOptions): void; + // 媒体-----录音 + interface StartRecordAudioOptions extends BaseOptions { + /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 开始录音。当主动调用swan.stopRecord, + * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 + * 注:文件的临时路径,在小程序本次启动期间可以正常使用, + * 如需持久保存,需在主动调用swan.saveFile,在小程序下次启动时才能访问得到。 + * @deprecated 1.6.0 + */ + function startRecord(options: StartRecordAudioOptions): void; + + interface StopRecordAudioOptions extends BaseOptions { + success?(res: TempFileResponse): void; + } + /** + * 主动调用停止录音。 + */ + function stopRecord(options?: StopRecordAudioOptions): void; + type EncodeBitRate = + | 8000 + | 11025 + | 12000 + | 16000 + | 22050 + | 24000 + | 32000 + | 44100 + | 48000; + interface RecorderManagerStartOptions { + /** + * 指定录音的时长,单位 ms + * 如果传入了合法的 duration + * 在到达指定的 duration 后会自动停止录音,最大值 600000(10 分钟),默认值 60000(1 分钟) + */ + duration?: number; + /** + * 采样率,有效值 8000/16000/44100 + */ + sampleRate?: number; + /** + * 否 录音通道数,有效值 1/2 + */ + numberOfChannels?: number; + /** + * 编码码率 + * 采样率和码率有一定要求,具体有效值如下: + * 采样率 编码码率 + * + 8000 16000 ~ 48000 + * + 11025 16000 ~ 48000 + * + 12000 24000 ~ 64000 + * + 16000 24000 ~ 96000 + * + 22050 32000 ~ 128000 + * + 24000 32000 ~ 128000 + * + 32000 48000 ~ 192000 + * + 44100 64000 ~ 320000 + * + 48000 64000 ~ 320000 + */ + encodeBitRate: number; + /** 音频格式,有效值 aac/mp3 */ + format: string; + } + interface OnRecorderManagerStopOptions { + tempFilePath: string; + } + interface OnFrameRecordedOptions { + /** 录音分片结果数据 */ + frameBuffer: ArrayBuffer; + /** 当前帧是否正常录音结束前的最后一帧 */ + isLastFrame: boolean; + } + interface RecorderManager { + /** 开始录音 */ + start(options?: RecorderManagerStartOptions): void; + /** 暂停录音 */ + pause(): void; + /** 继续录音 */ + resume(): void; + /** 停止录音 */ + stop(): void; + /** 录音开始事件 */ + onStart(callback?: () => void): void; + /** 录音暂停事件 */ + onPause(callback?: () => void): void; + /** 录音恢复事件 */ + onResume(callback?: () => void): void; + /** 录音停止事件,会回调文件地址 */ + onStop(callback?: (options: OnRecorderManagerStopOptions) => void): void; + /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ + onFrameRecorded(callback?: (options: OnFrameRecordedOptions) => void): void; + /** 录音错误事件, 会回调错误信息 */ + onError(callback?: (err: ErrMsgResponse) => void): void; + } + /** + * 获取全局唯一的录音管理器 recorderManager + * @version 1.6.0 + */ + function getRecorderManager(): RecorderManager; + // 媒体-----音频播放控制 + interface PlayVoiceOptions extends BaseOptions { + /** 需要播放的语音文件的文件路径 */ + filePath: string; + } + /** + * 开始播放语音,同时只允许一个语音文件正在播放, + * 如果前一个语音文件还没播放完,将中断前一个语音播放。 + * @deprecated 1.6.0 + */ + function playVoice(options: PlayVoiceOptions): void; + /** + * 暂停正在播放的语音。 + * 再次调用swan.playVoice播放同一个文件时,会从暂停处开始播放。 + * 如果想从头开始播放,需要先调用 swan.stopVoice。 + * @deprecated 1.6.0 + */ + function pauseVoice(): void; + /** + * 结束播放语音。 + * @deprecated 1.6.0 + */ + function stopVoice(): void; + // 媒体-----音乐播放控制 + interface BackgroundAudioPlayerState { + /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ + duration: number; + /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ + currentPosition: number; + /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ + status: number; + /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ + downloadPercent: number; + /** 歌曲数据链接,只有在当前有音乐播放时返回 */ + dataUrl: string; + } + interface GetBackgroundAudioPlayerStateOptions extends BaseOptions { + /** 接口调用成功的回调函数 */ + success?(state: BackgroundAudioPlayerState): void; + /** 接口调用失败的回调函数 */ + fail?(): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(): void; + } + /** + * 获取音乐播放状态。 + * @deprecated 1.2.0 + */ + function getBackgroundAudioPlayerState( + options: GetBackgroundAudioPlayerStateOptions + ): void; + interface PlayBackgroundAudioOptions extends BaseOptions { + /** 音乐链接 */ + dataUrl: string; + /** 音乐标题 */ + title?: string; + /** 封面URL */ + coverImgUrl?: string; + } + /** + * 播放音乐,同时只能有一首音乐正在播放。 + * @deprecated 1.2.0 + */ + function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; + /** + * 暂停播放音乐。 + * @deprecated 1.2.0 + */ + function pauseBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + interface SeekBackgroundAudioOptions extends BaseOptions { + /** 音乐位置,单位:秒 */ + position: number; + } + /** + * 控制音乐播放进度。 + * @deprecated 1.2.0 + */ + function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; + /** + * 停止播放音乐。 + * @deprecated 1.2.0 + */ + function stopBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + /** + * 监听音乐播放。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPlay(callback: () => void): void; + /** + * 监听音乐暂停。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPause(callback: () => void): void; + /** + * 监听音乐停止。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioStop(callback: () => void): void; + interface BackgroundAudioManager { + /** 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 */ + readonly duration: number; + /** 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 */ + readonly currentTime: number; + /** 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 */ + readonly paused: boolean; + /** 音频的数据源,默认为空字符串,当设置了新的 src 时,会自动开始播放 ,目前支持的格式有 m4a, aac, mp3, wav */ + src?: string; + /** 音频开始播放的位置(单位:s) */ + startTime?: number; + /** 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲。 是 */ + buffered: number; + /** 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 */ + title?: string; + /** 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + epname?: string; + /** 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + singer?: string; + /** 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 */ + coverImgUrl?: string; + /** 播放 */ + play(): void; + /** 暂停 */ + pause(): void; + /** 停止 */ + stop(): void; + /** 跳转到指定位置,单位 s */ + seek(position: number): void; + /** 背景音频进入可以播放状态,但不保证后面可以流畅播放 */ + onCanplay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放事件 */ + onPlay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频暂停事件 */ + onPause(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频停止事件 */ + onStop(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频自然播放结束事件 */ + onEnded(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放进度更新事件 */ + onTimeUpdate(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放错误事件 */ + onError(callback: (res: ErrCodeResponse) => void): void; + /** 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ + onWaiting(callback: (res: ErrCodeResponse) => void): void; + } + /** + * 获取全局唯一的背景音频管理器 backgroundAudioManager。 + * @version 1.2.0 + */ + function getBackgroundAudioManager(): BackgroundAudioManager; + // 媒体-----音频组件控制 + /** + * audioContext 通过 audioId 跟一个