第六章总结

 API应用

6.1.网络API

         微信小程序处理的数据通常从后台服务器获取,再将处理过的结果保存到后台服务器,这就要求微信小程序要有与后台进行交互的能力。

        网络API可以帮助开发者实现网络URL访问调用、文件的上传和下载、网络套接字的使用等功能处理。

1 发起网络请求

wx.request(0bject)实现向服务器发送请求、获取数据等各种网络交互操作,其相关参数如表所示。

通过 wx.requesl(0bject)获取百度(https:// www,baidu.com)首页的数据。

代码:

 
Page({
  data:{
    html:''
  },
  getbaidutap:function(){
    var that=this;
    wx.request({
      url: 'https://www.baidu.com',//百度网址
      data:{},//发送数据为空
      header:{"Content-Type":"application/json"},
      success:function(res){
        console.log(res);
        that.setData({
          html:res.data
        })
      }
    })
  }
})

2 上传文件

        wx.uploadFile(Object)接口用于将本地资源上传到开发者服务器,并在客户端发起一个HTTPS POST请求,其相关参数如表所示

代码:

 
Page({
data:{
  img:null,
},
uploadumage:function(){
  var that=this;
  //选择图片
  wx.chooseImage({
    success:function(res){
      var tempFilePaths=res.tempFilePaths
      upload(that.tempFilePaths);
    }
  })
  //显示toast提示消息
function upload(page,path){
  wx.showToast({
    icon:'loading',
    title: '正在上传'
  }),
  wx.uploadFile({
    filePath: path[0],
    name: 'file',
    url: 'http://localhost/',
    success:function(res){
      console.log(res);
      if(res.statusCode!=200){
        wx.showModal({
          title:"提示",
          content:"上传失败",
          showCancel:false
        })
        return;
      }
      var data=res.data
      //上传成功修改显示头像
      page.setData({
          img:path[0]
      })
    },
    fail:function(e){
      console.log(e);
      wx.showModal({
        title:"提示",
        content:"上传失败",
        showCancel:false
      })
    },
    //隐藏Toast
    complete:function(){
      wx.hideToast();
    }
  })
  }
}
})

3 下载文件

        wx.downloadFile(Objeet)接口用于实现从开发者服务器下载文件资源到本地,在客户端
直接发起一个HITPGET请求,返回文件的本地临时路径。

 
Page({
  datd:{
    img:null
  },
  downloadimage:function(){
    var that=this;
    wx.downloadFile({
      //通过WAMP软件实现
      url: 'http://localhost/1.jpg',
      success:function(res){
        console.log(res)
        that.setData({
          img:res.tempFilePath
        })
      }
    })
  }
})

2 多媒体 API

        多媒体API主要包括图片API、录音API、音频播放控制AP1、音乐播放控制API等,其目的是丰富小程序的页面功能

1.选择图片或拍照

        wx.chooselmage(Object)接口用于从本地相册选择图片或使用相机拍照。

 
Page({
  wx.chooseImage({
    //默认值为9
    count:2,
    //可以指定是原图还是压缩图,默认二者都有
    sizeType:['original','compressed'],
    //可以指定来源是相册还是相机,默认二者都有
    sourceType:['album','camera'],
    success:function(res){
    //返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的sec属性来显示图片
    var tempFilePaths=res.tempFilePaths
    var tempFiles=res.tempFiles
    console.log(tempFilePaths)
    console.log(tempFiles)
  }
  })
})
2.预览图片

        wx.previewlmage(0bject)接口主要用于预览图片

page({
wx.previewImage({
    current:"http://bomob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png",
    urls: ["http://bomob-cdn-16488.b0.upaiyun.com/2018/02/05/1.png",
           "http://bomob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png",
           "http://bomob-cdn-16488.b0.upaiyun.com/2018/02/05/3.png"
  ],
  })
})
3.获取图片信息

        wx.getlmagelnfo(Object)接口用于获取图片信息

  wx.chooseImage({
    success:function(res){
      wx.getImageInfo({
        src: res.tempFilePaths[0],
        success:function(e){
          console.log(e.width)
          console.log(e.height)
        }
      })
    },
  })
4.保存图片到系统相册

        wx.savelmageToPhotosAlbum(Objee)接日用于保存图片到系统相册

  wx.chooseImage({
    success:function(res){
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePaths[0],
        success:function(e){
          console.log(e)
        }
      })
    },
  })

三.录音API
录音API提供了语音录制的功能,主要包括以下两个API接口:

(1)wx.stariRecord(Object)接口 用于实现开始录音。

(2)wx.stopRecord(Objeet)接日 用于实现主动调用停止录音.

1.开始录音
        wx. startRecord(0bject)接口用于实现开始录音。

3录音API

1.开始录音

2.停止录音

        ws.slopReeord(Objeet)接口用于实现主动调用停止录音.

代码:

  wx.startRecord({
    success:function(res){
      var tempFilePath=res.tempFilePath
    },
    fail:function(res){
      //录音失败
    }
  }),
  setTimeout(function() {
    //结束录音
    wx.stopRecord()
  },10000)

四.音频播放控制API
        音频播放控制API主要用于对语音媒体文件的控制,包括播放、暂停、停止及audio组件的控制.

1.播放语音
        wx.playVoice(Object)接口用于开始播放语音,同时只允许一个语音文件播放,如果前一个语音文件还未播放完,则中断前一个语音文件的播放

  wx.startRecord({
    success:function(res) {
      var tempFilePath=res.tempFilePath
      wx.playVoice({
        filePath: tempFilePath,
        complete:function() {
          
        }
      })
    }
  })
2.暂停播放

        wx.pauseVoice(0bject)用于暂停正在播放的语音。

代码:

  //结束播放
  wx.startRecord({
    success:function(res) {
      var tempFilePath=res.tempFilePath
      wx.playVoice({
        filePath: tempFilePath,
      })
      setTimeout(function() {
        //暂停播放
        wx.pauseVoice()
      },5000)
    }
  })
3.结束播放

        wx.stopVoice(Object)用于结束播放语音

代码

  // 结束播放
  wx.startRecord({
    success:function(res){
      var tempFilePath=res.tempFilePath
      wx.playVoice({
        filePath: tempFilePath,
      })
      setTimeout(function(){
        wx.stopVoice()
      },5000)
    }
  })
4  音乐播放控制API

        音乐播放控制API主要用于实现对背景音乐的控制,音乐文件只能是网络流媒体,不能是本地音乐文件。

1.播放音乐

        wx.playBackgroundudio(Object)用于播放音乐,同一时间只能有一首音乐处于播放状态

2.获取音乐播放状态

        wx. getBackgroundAudioPlayerState(Object)接口用于获取音乐播放状态

3.控制音乐播放进度

wx,seekBackgroundAudio(0bject)接口用于控制音乐播放进度

4.暂停播放音乐
wx.pauseBackgroundAudio()接口用于暂停播放音乐

5.停止播放音乐
wx.stopBackgroundAudio()接口用于停止播放音乐

6.监听音乐播放
        wx. onBackgroundAudioPlay(CallBack)接口用于实现监听音乐播放,通常被 wx. playBackgroundAudio(Object)方法触发,在CallBack中可改变播放图标

7.监听音乐暂停
        wx.onBackgroundAudioPause(CallBack)接口用于实现监听音乐暂停,通常被wx.pauseBackgroundAudio()方法触发。

8.监听音乐停止
        wx.onBackgroundAudioStop(CallBack)接口用于实现监听音乐停止,通常被音乐自然播放停止或wx.seekBackgroundAudio(Object)方法导致播放位置等于音乐总时长时触发。

9.案例展示
        以小程序music为案例来展示音乐API的使用。该小将司程序的4个页面文件分别为music.wxml、music.wxss、music.json。

代码:

.bgaudio{
  height: 350rpx;
  width: 350rpx;
  margin-bottom: 100rpx;
}
.control-viewimage{
  height: 64rpx;
  width: 64rpx;
  margin: 30rpx;
}
Page({
  data:{
    isplaying:false,
    coverImg:"",
      changedImg:false,
       music:{
         "url":"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/09/117e4a1b405195b18061299e2de89597.mp3",
         "title":"盛晓玫-有一天",
         "coverImg":"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/09/f604297140c9681880cc3d3e581f7724.jpg"
       },
  },
  onLoad:function(){
    this.onAudioState();
  },
  onAudioTap:function(event){
    if(this.data.isplaying){
      wx.pauseBackgroundAudio();
    }else{
      let music=this.data.music;
      wx.playBackgroundAudio({
        dataUrl: music.url,
        title:music.title,
        coverImgUrl:music.coverImg
      })
    }
  },
  onStopTap:function(){
    let that=this;
    wx.stopBackgroundAudio({
      success:function(){
        that.setData({
          isplaying:false,changedImg:false
        });
      }
    })
  },
  onPositionTap:function(event){
    let how=event.target.dataset.how;
    wx.getBackgroundAudioPlayerState({
      success:function(res){
        let status=res.status;
        if(status===1){
          let duration=res.duration;
          let currentPosition=res.currentPosition;
          if(how==="0"){
            let position=currentPosition-10;
            if(position<0){
              position=1;
            }
            wx.setBackgroundAudio({
              position:position
            });
            wx.showToast({
              title: '快退10s',
              duration:500
            });
          }
          if(how==="1"){
            let position=currentPosition+10;
            if(position>duration){
              position=duration-1;
            }
            wx.seekBackgroundAudio({
              position: position
            });
            wx.showToast({
              title: '快进10s',
              duration:500
            });
          }
        }else{
          wx.showToast({
            title: '音乐未播放',
            duration:800
          });
        }
      }
    })
  },
  onAudioState:function(){
    let that=this;
    wx.onBackgroundAudioPlay(function(){
      that.setData({
        isplaying:true,
        changedImg:true
      });
      console.log("on play");
    });
    wx.onBackgroundAudioPause(function(){
      that.setData({
        isplaying:false
      });
      console.log("on pause");
    });
    wx.onBackgroundAudioStop(function(){
      that.setData({
        isplaying:false,
        changedImg:false
      });
      console.log("on stop")
    });
  }
})
<view class="container">
<image class="bgaudio"src = "{{changedImg? music.coverImg:'/pages/image/1.jpg'}}"/>
<view class ="control-view">
<!--使用data-how定义一个0表示快退10秒-->
<image src ="/pages/image/1.jpg"bindtap="onPositionTap"data-how= "0 "/>
<image src = "/pages/image/1.jpg" bindtap = "onAudioTap"/>
<image src ="/pages/image/1.jpg"bindtap = "onStopTap"/><!--使用data-how定义一个1表示快进10秒-->
<image src ="/pages/image/1.jpg"bindtap ="onPositionTap"data-how = "1"/>
</view >
</view >

6.3文件API

1.保存文件

Page({
  saveImage:function(){
    wx.chooseImage({
      count:1,
      sizeType:['original','compressed'],
      sourceType:['album','camera'],
      success:function(res){
        var tempFilePaths=res.tempFilePaths[0]
        wx.saveFile({
          tempFilePath:tempFilePaths,
          success:function(res){
            var saveFilePath=res.savedFilePath;
            console.log(saveFilePath)
          }
        })
      }
    })
  }
})

2.获取本地文件列表

wx.getSavedFileList({
  success:function(res){
    that.setData({
      fileList:res.fileList
    })
  }
})

3.获取本地文件的文件信息

wx.chooseImage({
  count:1,
  sizeType:['original','compressed'],
  sourceType:['album','camera'],
    success:function(res){
      var tempFilePaths=res.tempFilePaths[0]
      wx.saveFile({
        tempFilePath:tempFilePaths,
        success:function(res){
          var saveFilePath=res.savedFilePath;
          wx.getSavedFileInfo({
            filePath:saveFilePath,
            success:function(res){
              console.log(res.size)
            }
          })
        }
      })
    }
  })

4.删除本地文件

wx.getSavedFileList({
    success:function(res){
      if(res.fileList.length>0){
      wx.removeSaveFile({
       FilePath:res.fileList[0].filePath,
       complete:function(res){
              console.log(res)
            }
          })
        }
      }
      })

5.打开文档

wx.downloadFile({
  url: 'http://localhost/fm2.pdf',
  success:function(res){
    var tempFilePath=res.tempFilePath;
    wx.openDocument({
      filePath: 'tempFilePath',
      success:function(res){
        console.log("打开成功")
      }
    })
  }
})

6.4本地数据及缓存API

6.4.1保存数据

1.wx.setStorage(Object)

wx.setStorage({
  key:'name',
  data:'sdy',
  success:function(res){
    console.log(res)
  }
})

2.wx.setStorageSync(key,data)

js代码

wx.setStorageSync('age', '25')

6.4.2获取数据

1.wx.setStorage(Object)

wx.getStorage({
  key:'name',
  success:function(res){
    console.log(res.data)
  },
})

2.wx.setStorageSync(key)

js代码

try{
  var value =wx.getStorageSync('age')
  if(value){
    console.log("获取成功"+value)
  }
}catch(e){
  console.log("获取失败")
}

6.4.3删除数据

1.wx.removeStorage(Object)

wx.removeStorage({
  key: 'name',
  success:function(res){
    console.log("删除成功")
  },
  fail:function(){
    console.log("删除失败")
  }
})

2.wx.removeStorageSync(key)

js代码

try{
  wx.removeStorageSync('name')
}catch(e){
  
}

6.4.4清空数据

1.wx.clearStorage()

js代码

wx.getStorage({
  key: 'name',
  success:function(res){
   wx.clearStorage()
  },
})

2.wx.clearStorageSync()

js代码

try{
  wx.clearStorageSync()
}catch(e){
 
}

6.5位置信息API

6.5.1获取位置信息

js代码

wx.getLocation({
  type:'wgs84',
    success:function(res){
      console.log("经度"+res.longitude);
      console.log("纬度度"+res.latitude);
      console.log("速度"+res.longitude);
      console.log("位置的精确度"+res.accuracy);
      console.log("水平精确度"+res.horizontalAccuracy);
      console.log("垂直精确度"+res.verticalAccuracy);
    }
})

6.5.2选择位置信息

js代码

wx.chooseLocation({
    success:function(res){
      console.log("位置的名称"+res.longitude)
      console.log("位置的地址"+res.accuracy)
      console.log("位置的纬度"+res.horizontalAccuracy)
      console.log("位置的纬度"+res.verticalAccuracy)
    }
})

6.5.3显示位置信息

js代码

wx.getLocation({
  type:'gcj02',
    success:function(res){
      var latitude=res.latitude
      var longitude=res.longitude
      wx.openLocation({
        latitude: latitude,
        longitude: longitude,
        scale:10,
        name:'智慧国际酒店',
        address:'西安市长安区西长安区300号'
      })
    }
})

6.6设备相关API

6.6.1获取系统信息

js代码

wx.getSystemInfo({
    success:function(res){
      console.log("手机型号:"+res.model);
      console.log("设备像素比:"+res.pixelRatio);
      console.log("窗口的高度:"+res.windowHeight);
      console.log("窗口的宽度:"+res.windowWidth);
      console.log("微信的版本号:"+res.version);
      console.log("操作系统版本:"+res.system);
      console.log("客户端平台:"+res.platform);
    },
})

6.6.2网络状态

1.获取网络状态

js代码

wx.getNetworkType({
  success:function(res){
    console.log(res.networkType)
  },
})

2.监听网络状态变化

js代码

wx.onNetworkStatusChange({function(res){
  console.log("网络是否链接"+res.isConnected)
  console.log("变化后的网络类型"+res.networkType)
}
})

6.6.3拨打电话

js代码

wx.makePhoneCall({
  phoneNumber: '18092585093',
})

6.6.4扫描二维码

js代码

wx.scanCode({
  success:(res)=>{
    console.log(res.result)
    console.log(res.scanType)
    console.log(res.charSet)
    console.log(res.path)
  }
})

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值