wx.setClipboardData
這是微信小程序提供的 API,用于將數據復制到剪貼板。
Page({data: {clientInfo: {email: 'example@example.com' // 假設的郵箱數據}},// 復制郵箱到剪貼板copyEmail: function() {wx.setClipboardData({data: this.data.clientInfo.email,success(res) {console.log('郵箱復制成功');wx.showToast({title: '已復制郵箱',icon: 'success'});},fail(err) {console.error('復制失敗:', err);wx.showToast({title: '復制失敗',icon: 'none'});}});}
});
wx.saveImageToPhotosAlbum
功能:
- 將指定 URL 的圖片保存到用戶相冊。
- 要處理用戶未授權時的邏輯,引導用戶開啟相冊權限。
wx.saveImageToPhotosAlbum({filePath: url,success: () => {// 保存成功},fail: (err) => {// 沒有權限,彈出提示請求授權if (err.errMsg.includes("auth denied") || err.errMsg.includes("authorize no response")) {wx.showModal({title: '提示',content: '需要您授權保存相冊',success: (res) => {if (res.confirm) {wx.openSetting({success: (settingdata) => {if (settingdata.authSetting['scope.writePhotosAlbum']) {this.savePosteToPhoto(url); // 重新嘗試保存} else {wx.showToast({ title: '獲取權限失敗', icon: 'none', duration: 3000 });}}});} else {//取消授權wx.showToast({ title: '取消授權', icon: 'none', duration: 3000 });}},fail: () => {wx.showToast({ title: '取消授權', icon: 'none', duration: 3000 });}});} else {wx.showToast({ title: '取消保存', icon: 'none', duration: 3000 });}}
});
wx.showShareImageMenu)
功能:
- 調起微信分享圖片的菜單。
- 需要用戶主動觸發(如按鈕點擊),否則無法使用。
wx.showShareImageMenu({path: url // 指定分享的圖片路徑
});
wx.downloadFile + wx.saveVideoToPhotosAlbum 下載文件并保存到相冊
//下載文件
wx.downloadFile({url: url,success: (res) => {//保存到相冊wx.saveVideoToPhotosAlbum({filePath: res.tempFilePath,success: () => {wx.showToast({ title: '保存成功', icon: 'success' });},fail: (err) => {//沒有權限,需要授權if (err.errMsg.includes("auth denied") || err.errMsg.includes("authorize no response")) {wx.showModal({title: '提示',content: '需要您授權保存相冊',success: (res) => {if (res.confirm) {wx.openSetting({success: (settingdata) => {if (settingdata.authSetting['scope.writePhotosAlbum']) {this.save(); // 授權后,重新保存} else {wx.showToast({ title: '獲取權限失敗', icon: 'none', duration: 3000 });}}});} else {wx.showToast({ title: '取消授權', icon: 'none', duration: 3000 });}}});} else {wx.showToast({ title: '取消保存', icon: 'none', duration: 3000 });}}});}
});
使用原生的小程序開發進行if判斷時,就會出現嵌套,代碼的可讀性也就會變差,如果把他們封裝成函數,上面的授權過程就會好理解些,為了理解這個過程,這里不用小程序的格式封裝了,在小程序中不能這樣寫,這里只是一個例子。
總結下來一共就進行了三步:
- downloadFile下載文件,
- 確認有沒有保存到相冊的權限,沒有就授權,
- 保存到相冊
// 公共函數:處理相冊權限
function checkPhotoAlbumPermission(successCallback) {wx.showModal({title: '提示',content: '需要您授權保存相冊',success: (res) => {if (res.confirm) {wx.openSetting({success: (settingdata) => {if (settingdata.authSetting['scope.writePhotosAlbum']) {successCallback(); // 授權成功后執行回調} else {wx.showToast({ title: '獲取權限失敗', icon: 'none', duration: 3000 });}}});} else {wx.showToast({ title: '取消授權', icon: 'none', duration: 3000 });}}});
}// 保存圖片到相冊
function saveImage(url) {wx.saveImageToPhotosAlbum({filePath: url,success: () => wx.showToast({ title: '保存成功', icon: 'success' }),fail: (err) => {if (err.errMsg.includes("auth denied")) {checkPhotoAlbumPermission(() => saveImage(url));} else {wx.showToast({ title: '保存失敗', icon: 'none', duration: 3000 });}}});
}// 下載并保存視頻
function saveVideo(videoUrl) {wx.downloadFile({url: videoUrl,success: (res) => {wx.saveVideoToPhotosAlbum({filePath: res.tempFilePath,success: () => wx.showToast({ title: '保存成功', icon: 'success' }),fail: (err) => {if (err.errMsg.includes("auth denied")) {checkPhotoAlbumPermission(() => saveVideo(videoUrl));} else {wx.showToast({ title: '保存失敗', icon: 'none', duration: 3000 });}}});},fail: () => {wx.showToast({ title: '下載失敗', icon: 'none', duration: 3000 });}});
}
錄音
// 初始化錄音管理器
const recorderManager = wx.getRecorderManager();// 開始錄音startRecord() {// 設置一些參數const options = { duration: 60000, // 最長 60 秒sampleRate: 16000, // 采樣率 16kHznumberOfChannels: 1, // 單聲道encodeBitRate: 96000, // 編碼碼率 96kbpsformat: "mp3", // 音頻格式frameSize: 50, // 幀大小 50KB};// 檢查麥克風權限wx.getSetting({success: (res) => {if (!res.authSetting["scope.record"]) {wx.authorize({scope: "scope.record",success: () => {recorderManager.start(options);this.startCountDown();},fail: () => {wx.showToast({ title: "未授權麥克風權限", icon: "none" });},});} else {// 開始錄音recorderManager.start(options);// 設置倒計時this.startCountDown();}},});},// 開始計時startCountDown() {let seconds = 0;const maxTime = 60this.recordTimer = setInterval(() => {seconds++;// 到時間停止錄音if (seconds > maxTime) {clearInterval(this.recordTimer);recorderManager.stop();return;}// 格式化顯示時間(00:00)const minutes = Math.floor(seconds / 60);const remainingSeconds = seconds % 60;const displayTime = `${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;this.setData({"duration": displayTime,});}, 1000);},// 停止錄音endRecord() {clearInterval(this.recordTimer);recorderManager.stop();},// 上傳錄音文件uploadAudio(tempFilePath) {wx.showLoading({ title: "上傳中...", mask: true });wx.uploadFile({filePath: tempFilePath,url: "https://example.com/api/uploadVoice",name: "file",header: {"content-type": "multipart/form-data","token": "YOUR_TOKEN",},formData: {},success: (res) => {const response = JSON.parse(res.data);if (response.code === 0) {wx.showToast({ title: "上傳成功", icon: "success" });} else {wx.showToast({ title: "上傳失敗", icon: "none" });}},fail: (err) => {wx.showToast({ title: "網絡錯誤", icon: "none" });},complete: () => {wx.hideLoading();},});},
播放音頻
// 創建一個微信小程序的音頻上下文對象。//wx.createInnerAudioContext:微信小程序的 API,用于創建音頻播放實例。// useWebAudioImplement: false:指定不使用 WebAudio 實現,而是使用原生實現。
const speakerAudioContext = wx.createInnerAudioContext({ useWebAudioImplement: false });onLoad() {// 監聽音頻事件this.setupAudioEvents();},
});
//監聽時間,這里有個坑,有時候監聽事件不生效,監聽的時機不對
setupAudioEvents() {// 播放開始speakerAudioContext.onPlay(() => {});});// 播放結束speakerAudioContext.onEnded(() => {});// 播放錯誤speakerAudioContext.onError((err) => {console.error("音頻播放錯誤", err);});
},// 播放音頻
playVoice() {//暫停時重新播放if (this.data.voicePause) {speakerAudioContext.play(); // 繼續播放//其他操作} else {//播放新的speakerAudioContext.src = ‘xxx’speakerAudioContext.play();}
},// 暫停音頻
pauseVoice() {speakerAudioContext.pause();// 其他操作
},// 停止音頻
stopVoice() {speakerAudioContext.stop();// 其他操作
},
// 調整音量
setVolume(e) {speakerAudioContext.volume = 1;
},
訂閱消息
Page({data: {// 訂閱消息模板 ID(需從微信公眾平臺獲取)tmplIds: ["HURj2vKkoldzDj9LVLz59jLq2WPZCBxbkDS5qbYzHTE"],},// 訂閱消息主流程subscribeProc() {const { tmplIds } = this.data;// 1. 檢查訂閱權限wx.getSetting({withSubscriptions: true,success: (res) => {const status = res.subscriptionsSetting[tmplIds[0]];// 情況 1:用戶已拒絕,引導打開設置頁if (status === "reject" || status === "ban") {this.showAuthModal();} // 情況 2:未拒絕,直接彈窗訂閱else {this.requestSubscribe();}},fail: (err) => {console.error("檢查權限失敗", err);wx.showToast({ title: "檢查權限失敗", icon: "none" });},});},// 顯示授權引導彈窗showAuthModal() {wx.showModal({title: "訂閱權限已關閉",content: "需要您授權訂閱消息,是否去設置打開?",confirmText: "去設置",success: (res) => {if (res.confirm) {wx.openSetting({success: (res) => {console.log("用戶已打開設置頁", res);},});}},});},// 請求訂閱消息requestSubscribe() {const { tmplIds } = this.data;wx.requestSubscribeMessage({tmplIds: tmplIds,success: (res) => {const status = res[tmplIds[0]];console.log("訂閱結果", res);// 用戶同意訂閱if (status === "accept") {wx.showToast({ title: "訂閱成功", icon: "success" });this.subscribeSend(); // 執行訂閱后的邏輯} // 用戶拒絕訂閱else {wx.showToast({ title: "已取消訂閱", icon: "none" });}},fail: (err) => {console.error("訂閱失敗", err);wx.showToast({ title: "訂閱失敗", icon: "none" });},});},// 訂閱成功后發送消息(示例)subscribeSend() {wx.request({url: "https://example.com/api/sendSubscribeMsg",method: "POST",data: {tmplId: this.data.tmplIds[0],userId: "123",},success: (res) => {console.log("消息發送成功", res);},fail: (err) => {console.error("消息發送失敗", err);},});},
});
選擇照片,并上傳
wx.chooseImage({count: 1,sizeType: ['original'],sourceType: ['album', 'camera'],success(res) {console.log(res) const src = res.tempFilePaths[0];wx.uploadFile({url: url,filePath: src,name: "file",header: {"content-type":"multipart/form-data",'token': token,}, // 按需success: (res) => {},fail: (err) => {console.log(err)}})}})