wx.setClipboardData
这是微信小程序提供的 API,用于将数据复制到剪贴板。
js
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 的图片保存到用户相册。
- 要处理用户未授权时的逻辑,引导用户开启相册权限。
js
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)
功能:
- 调起微信分享图片的菜单。
- 需要用户主动触发(如按钮点击),否则无法使用。
js
wx.showShareImageMenu({
path: url // 指定分享的图片路径
});
wx.downloadFile + wx.saveVideoToPhotosAlbum 下载文件并保存到相册
js
//下载文件
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下载文件,
- 确认有没有保存到相册的权限,没有就授权,
- 保存到相册
js
// 公共函数:处理相册权限
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 });
}
});
}
录音
js
// 初始化录音管理器
const recorderManager = wx.getRecorderManager();
// 开始录音
startRecord() {
// 设置一些参数
const options = {
duration: 60000, // 最长 60 秒
sampleRate: 16000, // 采样率 16kHz
numberOfChannels: 1, // 单声道
encodeBitRate: 96000, // 编码码率 96kbps
format: "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 = 60
this.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();
},
});
},
播放音频
js
// 创建一个微信小程序的音频上下文对象。
//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;
},
订阅消息
js
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);
},
});
},
});
选择照片,并上传
js
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)
}
})
}
})