You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
study_helper/pages/study/study.js

418 lines
11 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// pages/study/study.js
const innerAudioContext = wx.createInnerAudioContext()
Page({
data: {
poemTitle: '加载中...',
poetInfo: '',
originalText: '',
translationText: '',
backgroundInfo: '',
showTranslation: false,
showBackground: false,
poem: null,
isLoading: true,
authorInfo: '',
loadError: false,
poemType: '',
token: ''
},
onLoad(options) {
console.log('学习页面参数:', options);
this.options = options;
// 初始化语音上下文事件监听
this.initAudioEvents();
// 获取token
this.getToken();
if (options.poemData) {
// 从首页传递的完整诗歌数据
try {
const poemData = decodeURIComponent(options.poemData);
const poem = JSON.parse(poemData);
console.log('解析后的诗歌数据:', poem);
this.processPoemData(poem);
} catch (error) {
console.error('解析诗歌数据失败:', error);
this.showError('数据解析失败');
}
} else if (options.id) {
// 根据ID从数据库加载诗词数据
console.log('通过ID加载诗歌:', options.id);
this.loadPoemFromDatabase(options.id);
} else {
this.showError('缺少诗歌信息');
}
},
// 初始化音频事件监听
initAudioEvents() {
innerAudioContext.onPlay(() => {
console.log('开始播放语音');
});
innerAudioContext.onStop(() => {
console.log('停止播放语音');
});
innerAudioContext.onEnded(() => {
console.log('语音播放结束');
});
innerAudioContext.onError((res) => {
console.error('语音播放错误:', res);
wx.showToast({
title: '语音播放失败',
icon: 'none'
});
});
},
// 获取token复用recite.js中的逻辑
getToken() {
let that = this;
wx.getStorage({
key: 'expires_in',
success(res) {
console.log("缓存中有access_token");
console.log("token失效时间", res.data);
const newT = new Date().getTime();
// 用当前时间和存储的时间判断token是否已过期
if (newT > parseInt(res.data)) {
console.log("token过期重新获取token");
that.fetchNewToken();
} else {
console.log("获取本地缓存的token");
that.setData({
token: wx.getStorageSync('access_token')
});
}
}, fail() {
console.log("缓存中没有access_token直接获取新token");
// 尝试从storage直接获取token
const token = wx.getStorageSync('access_token');
if (token) {
that.setData({ token: token });
} else {
// 直接获取新token不再依赖背诵功能初始化
that.fetchNewToken();
}
}
});
},
// 获取新token
fetchNewToken() {
let that = this;
let ApiKey = 'qdHcePu7v0WpIlJnaeGJZZqp';
let SecretKey = 'nuZCuBziZoO2gjE6NGEMKCdxKs4sbaNq';
const url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + ApiKey + '&client_secret=' + SecretKey;
wx.request({
url: url,
method: 'POST',
success(res) {
console.log("创建access_token成功", res);
// 将access_token存储到storage中
wx.setStorage({
key: 'access_token',
data: res.data.access_token
});
var date = new Date().getTime();
let time = date + 2592000 * 1000;
console.log('三十天后的时间', time);
wx.setStorage({
key: 'expires_in',
data: time
});
that.setData({
token: res.data.access_token
});
},
fail(err) {
console.error('获取token失败:', err);
wx.showToast({
title: '语音服务初始化失败',
icon: 'none'
});
}
});
},
// 语音合成播放函数
playstart(text) {
let that = this;
if (!that.data.token) {
wx.showToast({
title: '语音服务未初始化',
icon: 'none'
});
return;
}
console.log("开始语音合成", text);
// 对文本进行URL编码
const encodedText = encodeURIComponent(text);
innerAudioContext.src = 'https://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=12_56&tok=' + that.data.token + '&tex=' + encodedText + '&vol=10&per=111&spd=5&pit=5&aue=3';
innerAudioContext.play();
wx.showToast({
title: '开始朗读',
icon: 'success',
duration: 1000
});
},
// 从数据库加载诗歌数据
async loadPoemFromDatabase(id) {
try {
console.log('开始从数据库加载诗歌ID:', id);
wx.showLoading({
title: '加载中...',
});
const db = wx.cloud.database();
const result = await db.collection('poeties').doc(id).get();
wx.hideLoading();
console.log('数据库查询结果:', result);
if (result.data) {
this.processPoemData(result.data);
} else {
this.showError('诗歌不存在');
}
} catch (error) {
wx.hideLoading();
console.error('数据库查询失败:', error);
// 如果直接查询失败,尝试使用云函数
this.loadPoemFromCloudFunction(id);
}
},
// 云函数加载(备用方案)
async loadPoemFromCloudFunction(id) {
try {
console.log('尝试通过云函数加载诗歌ID:', id);
const result = await wx.cloud.callFunction({
name: 'getPoemDetail',
data: { id: id }
});
console.log('云函数返回结果:', result);
if (result.result && result.result.success) {
const poem = result.result.data;
this.processPoemData(poem);
} else {
this.showError(result.result?.message || '诗歌不存在');
}
} catch (error) {
console.error('调用云函数失败:', error);
}
},
// 处理诗歌数据
processPoemData(poem) {
console.log('处理诗歌数据:', poem);
// 设置页面数据
this.setData({
poem: poem,
poemTitle: poem.title || '未知标题',
poetInfo: this.formatPoetInfo(poem),
originalText: poem.content || '暂无内容',
translationText: poem.translation || '暂无译文',
backgroundInfo: poem.background || '暂无背景信息',
authorInfo: poem.author_info ? poem.author_info.intro : (poem.author ? `暂无${poem.author}的详细信息` : '暂无作者信息'),
poemType: poem.type || '诗',
isLoading: false,
loadError: false
});
// 设置导航栏标题
wx.setNavigationBarTitle({
title: poem.title || '古诗学习'
});
},
// 格式化作者信息
formatPoetInfo(poem) {
let info = '';
if (poem.dynasty) {
info += poem.dynasty;
}
if (poem.author) {
info += (info ? ' • ' : '') + poem.author;
}
return info || '未知信息';
},
// 切换译文显示状态
toggleTranslation() {
this.setData({
showTranslation: !this.data.showTranslation
});
},
// 切换背景信息显示状态
toggleBackground() {
this.setData({
showBackground: !this.data.showBackground
});
},
// 显示错误信息
showError(message) {
this.setData({
isLoading: false,
loadError: true,
poemTitle: '加载失败',
originalText: message
});
wx.showToast({
title: message,
icon: 'none',
duration: 2000
});
},
// 重新加载
reloadData() {
const options = this.options || {};
if (options.id) {
this.setData({ isLoading: true, loadError: false });
this.loadPoemFromDatabase(options.id);
} else {
wx.navigateBack();
}
},
// 复制诗歌内容
copyContent() {
const content = this.data.originalText;
wx.setClipboardData({
data: content,
success: () => {
wx.showToast({
title: '已复制到剪贴板',
icon: 'success'
});
}
});
},
// 语音播报功能(支持不同类型内容的朗读)
speakPoem(e) {
// 获取要朗读的内容类型
const contentType = e?.currentTarget?.dataset?.type || 'all';
let textToSpeak = '';
let title = '';
switch(contentType) {
case 'content':
textToSpeak = this.data.originalText;
title = '朗读原文';
break;
case 'translation':
textToSpeak = this.data.translationText;
title = '朗读译文';
break;
case 'background':
textToSpeak = this.data.backgroundInfo;
title = '朗读背景';
break;
case 'author':
textToSpeak = this.data.authorInfo;
title = '朗读作者简介';
break;
default:
// 默认朗读全部内容(包括题目、作者、原文、译文、背景、作者简介)
textToSpeak = `${this.data.poemTitle}${this.data.poetInfo}${this.data.originalText}${this.data.translationText}${this.data.backgroundInfo}${this.data.authorInfo}`;
title = '语音播报';
}
console.log(`准备朗读${contentType}内容:`, textToSpeak);
// 调用语音合成播放函数
this.playstart(textToSpeak);
},
// 分享功能
onShareAppMessage() {
const poem = this.data.poem;
if (poem && poem._id) {
return {
title: `${poem.title} - ${poem.author}`,
path: `/pages/study/study?id=${poem._id}`
};
}
return {
title: `${this.data.poemTitle}`,
path: '/pages/study/study'
};
},
onReady() {
// 可以在这里添加动画效果等
},
onShow() {
// 页面显示时的逻辑
},
onHide() {
},
onUnload() {
},
onPullDownRefresh() {
const options = this.options || {};
if (options.poemData) {
// 如果是传递完整数据,不需要重新加载
wx.stopPullDownRefresh();
} else if (options.id) {
this.loadPoemFromDatabase(options.id).then(() => {
wx.stopPullDownRefresh();
});
} else {
wx.stopPullDownRefresh();
}
},
onReachBottom() {
// 可以在这里添加加载更多相关内容
},
// 跳转到背诵页面
goToRecite() {
const poem = this.data.poem;
if (poem && poem._id) {
console.log('跳转到背诵页面诗歌ID:', poem._id);
// 将诗歌数据编码后传递给背诵页面
const poemData = encodeURIComponent(JSON.stringify(poem));
wx.navigateTo({
url: `/pages/recite/recite?id=${poem._id}&poemData=${poemData}`
});
} else {
wx.showToast({
title: '背诵功能暂不可用',
icon: 'none'
});
}
}
})