otherContent如果content内容是图片,存宽高

This commit is contained in:
wuchunlei
2024-12-11 17:17:56 +08:00
parent 078f05d037
commit 0ac6ab33d5
7 changed files with 134 additions and 108 deletions

View File

@@ -21,35 +21,8 @@ public class BaiduVoicesUtils {
// 填写申请百度语音申请的appkey 申请地址百度AI开放平台
private final static String appKey = "WOKN473V1o1gL8WMsAkfJZIY";
private final static String secretKey = "CpgbKdB9aZu2esnq5lMdqRZG37Jn3a76";
//http://aipe-speech.bj.bcebos.com/text_to_speech/2024-12-06/6752c65ee615a10001435c06/speech/0.null?authorization=bce-auth-v1%2FALTAKjI91nE52nvtDNRgFlUCVz%2F2024-12-06T09%3A41%3A51Z%2F259200%2F%2F08aed96bc0e5808a83c1a80ee3a925866a2a7ac5b017e29670fe7951f713bbf6
public static void main(String[] arg){
try {
System.out.println(new Date().getTime());
// File audioFile = new File("F:\\111.wav");// 创建一个文件对象
// AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(audioFile);// 获音频文件格式
// float sampleRate = fileFormat.getFormat().getSampleRate();
// int samplesizeInBits = fileFormat.getFormat().getSampleSizeInBits();
// int aaa = fileFormat.getByteLength();
// System.out.println("sampleRate: " + sampleRate);
// System.out.println("samplesizeInBits: " + samplesizeInBits);
// System.out.println("aaa: " + aaa);
String text = "天地之道者 ,理也 万物之始者 气也 气之聚散者 象也; 物之终始者 ,数也 。为 医者尤需明理 ,理不明则法不清 法不清则 方药无凭 。 医之理者 ,病理也 然欲明病理 ,先知生理 ,故太湖无 中医基础理论课程而有生理 、病理 。生之理者 ,《 内经》 所谓人事 也 ,至于天人之学 尚需于太湖国学院求之 。经谓精光之论 大圣";
// shortText("补充一点,桂枝的主要有效成分是挥发油,大概占桂枝 重量的0.7%左右不到1%。桂枝挥发油有一个特点,它由呼 吸道排出,对呼吸道炎症有明显的抗炎、祛痰、止咳作用,所 以在麻黄汤里,桂枝既增强了麻黄的发汗作用,又增强了杏仁 的化痰止咳平喘作用。");
// System.out.println(JacobUtil.toVoice(text));
// MP3File file = new MP3File("F:/a.mp3");
// MP3AudioHeader audioHeader = (MP3AudioHeader)file.getAudioHeader();
// int intLen = audioHeader.getTrackLength();
// System.out.println(intLen);
System.out.println(new Date().getTime());
}catch (Exception e) {
e.printStackTrace();
}
}
//语音合并
public static String mergeVoices(List<String> urls){
try {
File outFile = File.createTempFile(UUID.randomUUID().toString(),".mp3",new File("..\\"));

View File

@@ -28,35 +28,24 @@ import java.util.UUID;
//文字转语音离线工具windows平台
public class JacobUtil {
public static String toVoice(String text) {
public static void toVoice(String text,File file) {
try {
//生成wav音频文件 直接生成MP3文件获取不到文件头转换一下才可以
File wavFile = File.createTempFile(UUID.randomUUID().toString(),".wav",new File("..\\"));
text(wavFile.getAbsolutePath(),text,100,0);
//wav转mp3文件
byte[] bytes = encodeToMp3(wavFile);
File file = File.createTempFile(UUID.randomUUID().toString(),".mp3",new File("..\\"));
FileCopyUtils.copy(bytes,file);
String fileUrl = uploadFile(file,".mp3");
if (StringUtils.isNotBlank(fileUrl)){
MP3File mp3File = new MP3File(file);
MP3AudioHeader audioHeader = (MP3AudioHeader)mp3File.getAudioHeader();
double intLen = audioHeader.getPreciseTrackLength();
BigDecimal bd = new BigDecimal(intLen);
bd = bd.setScale(4, BigDecimal.ROUND_HALF_UP);
file.delete();
fileUrl+=","+bd.toString();
}
file.delete();
return fileUrl;
wavFile.delete();
}catch (Exception e) {
e.printStackTrace();
return "";
}
}
//wav转mp3工具在项目resources-lib下有jar包
public static byte[] encodeToMp3(File wavFile) throws Exception {
InputStream wavTestFileInputStream = new BufferedInputStream(new FileInputStream(wavFile));
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(wavTestFileInputStream);
// LameEncoder encoder = new LameEncoder(audioInputStream.getFormat(), 256, MPEGMode.STEREO, Lame.QUALITY_HIGHEST, false);
LameEncoder encoder = new LameEncoder(audioInputStream.getFormat(), 128, MPEGMode.STEREO, Lame.QUALITY_HIGHEST, false);
ByteArrayOutputStream mp3 = new ByteArrayOutputStream();
byte[] inputBuffer = new byte[encoder.getPCMBufferSize()];
@@ -70,27 +59,6 @@ public class JacobUtil {
encoder.close();
return mp3.toByteArray();
}
public static String uploadFile(File file, String fileName) {
String endpoint = ConstantPropertiesUtils.END_POIND;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
try {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
fileName = uuid + fileName;
String datePath = new DateTime().toString("yyyy/MM/dd");
fileName = datePath + "/" + fileName;
ossClient.putObject(bucketName, fileName, file);
ossClient.shutdown();
String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static boolean text(String path, String text, int volume, int speed) {
try {

View File

@@ -56,22 +56,17 @@ public class BookChapterContentController {
private ShopProductBookService shopProductBookService;
//章节内容单句转成音频
//某一内容转成音频
@RequestMapping("/contentToVoices")
public R contentToVoices(@RequestBody Map<String,Object> params){
//调用百度语音合成 API
// String voices = BaiduVoicesUtils.shortText(params.get("content").toString());
String voices = JacobUtil.toVoice(params.get("content").toString());
if (StringUtils.isEmpty(voices)) {
return R.error("语音上传失败");
}
return R.ok().put("voices", voices);
bookChapterContentService.contentToVoices(params.get("bookChapterContentId").toString());
return R.ok();
}
//按一句话转成音频
//书籍下所有内容转成音频
@RequestMapping("/bookToShortVoices")
public R bookToShortVoices(@RequestBody Map<String,Object> params){
ExecutorService service = Executors.newFixedThreadPool(5);
ExecutorService service = Executors.newFixedThreadPool(10);
List<BookChapterContentEntity> list = bookChapterContentService.list(new LambdaQueryWrapper<BookChapterContentEntity>()
.eq(BookChapterContentEntity::getBookId,params.get("bookId")));
for (BookChapterContentEntity bcc:list){
@@ -79,20 +74,7 @@ public class BookChapterContentController {
service.execute(new Runnable() {
@Override
public void run() {
try {
//调用百度语音合成 API
// String voices = BaiduVoicesUtils.shortText(bcc.getContent());
String voices = JacobUtil.toVoice(bcc.getContent());
if (voices.contains(",")){
bcc.setVoices(voices.split(",")[0]);
bcc.setVoicesSize(voices.split(",")[1]);
}else {
bcc.setVoices(voices);
}
bookChapterContentService.updateById(bcc);
}catch (Exception e) {
e.printStackTrace();
}
bookChapterContentService.contentToVoices(bcc.getId()+"");
}
});
}
@@ -100,7 +82,7 @@ public class BookChapterContentController {
return R.ok();
}
//章节下所有音频合并成一个音频
//某一章节下所有音频合并成一个音频
@RequestMapping("/mergeVoices")
public R mergeVoices(@RequestBody Map<String,Object> params){
List<BookChapterContentEntity> bccs = bookChapterContentService.list(new LambdaQueryWrapper<BookChapterContentEntity>()
@@ -123,7 +105,7 @@ public class BookChapterContentController {
}
}
//所有章节合并音频
//所有章节合并各自音频
@RequestMapping("/mergeVoicesByBookId")
@Transactional
public R mergeVoicesByBookId(@RequestBody Map<String,Object> params){
@@ -131,25 +113,27 @@ public class BookChapterContentController {
List<BookChapterEntity> bcs = bookChapterService.list(new LambdaQueryWrapper<BookChapterEntity>()
.eq(BookChapterEntity::getBookId,params.get("bookId"))
.orderByAsc(BookChapterEntity::getNumber));
ExecutorService service = Executors.newFixedThreadPool(10);
for (BookChapterEntity bc:bcs) {
List<BookChapterContentEntity> bccs = bookChapterContentService.list(new LambdaQueryWrapper<BookChapterContentEntity>()
.eq(BookChapterContentEntity::getBookChatperId,bc.getId())
.orderByAsc(BookChapterContentEntity::getNumber));
List<String> list = new ArrayList<>();
for (BookChapterContentEntity bcc : bccs) {
if (!StringUtils.isEmpty(bcc.getVoices())){
list.add(bcc.getVoices());
service.execute(new Runnable() {
@Override
public void run() {
List<BookChapterContentEntity> bccs = bookChapterContentService.list(new LambdaQueryWrapper<BookChapterContentEntity>()
.eq(BookChapterContentEntity::getBookChatperId,bc.getId())
.orderByAsc(BookChapterContentEntity::getNumber));
List<String> list = new ArrayList<>();
for (BookChapterContentEntity bcc : bccs) {
if (!StringUtils.isEmpty(bcc.getVoices())){
list.add(bcc.getVoices());
}
}
String url = BaiduVoicesUtils.mergeVoices(list);
bc.setVoices(url);
bookChapterService.updateById(bc);
}
}
String url = BaiduVoicesUtils.mergeVoices(list);
if (!StringUtils.isEmpty(url)){
bc.setVoices(url);
bookChapterService.updateById(bc);
}else {
sb.append(bc.getChapter()+"-"+bc.getContent()+"错误");
}
});
}
return R.ok().put("info",sb.toString());
return R.ok();
}
//按章节转成长音频

View File

@@ -15,6 +15,8 @@ import java.util.Map;
*/
public interface BookChapterContentService extends IService<BookChapterContentEntity> {
void contentToVoices(String bccId);
PageUtils queryPage(Map<String, Object> params);
void getBookVoices(Integer id);

View File

@@ -1,20 +1,30 @@
package com.peanut.modules.book.service.impl;
import com.peanut.common.utils.FileDownloadUtil;
import com.peanut.common.utils.JacobUtil;
import com.peanut.modules.common.entity.BookChapterEntity;
import com.peanut.modules.common.entity.BookEntity;
import com.peanut.modules.book.service.BookChapterService;
import com.peanut.modules.book.service.BookService;
import com.peanut.modules.oss.service.OssService;
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.BreakIterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@@ -32,6 +42,44 @@ public class BookChapterContentServiceImpl extends ServiceImpl<BookChapterConten
private BookChapterService bookChapterService;
@Autowired
private BookService bookService;
@Autowired
private OssService ossService;
@Override
public void contentToVoices(String bccId) {
try {
BookChapterContentEntity bcc = this.getBaseMapper().selectById(bccId);
if (bcc != null&&StringUtils.isNotBlank(bcc.getContent())) {
//生成音频
File tempFile = File.createTempFile(UUID.randomUUID().toString(),".mp3",new File("..\\"));
JacobUtil.toVoice(bcc.getContent(),tempFile);
//上传
String uploadUrl = ossService.uploadFile(tempFile);
bcc.setVoices(uploadUrl);
//获取时长
MP3File mp3File = new MP3File(tempFile);
MP3AudioHeader audioHeader = (MP3AudioHeader)mp3File.getAudioHeader();
double intLen = audioHeader.getPreciseTrackLength();
BigDecimal bd = new BigDecimal(intLen);
bd = bd.setScale(4, BigDecimal.ROUND_HALF_UP);
bcc.setVoicesSize(bd.toString());
tempFile.delete();
this.getBaseMapper().updateById(bcc);
}
}catch (Exception e) {
e.printStackTrace();
}
}
@Override
public PageUtils queryPage(Map<String, Object> params) {

View File

@@ -3,12 +3,19 @@ package com.peanut.modules.oss.service;
import com.peanut.common.utils.R;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.InputStream;
public interface OssService {
//上传头像到oss
String uploadFileAvatar(MultipartFile file);
String uploadFileSchedule(MultipartFile file,String uid);
String uploadFile(File file);
String uploadFile(InputStream inputStream, String fileName);
String uploadHtml(String html,String name);
R getSchedule(String uid);

View File

@@ -15,6 +15,7 @@ import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.UUID;
@@ -76,6 +77,49 @@ public class OssServiceImpl implements OssService {
}
}
public String uploadFile(File file) {
String endpoint = ConstantPropertiesUtils.END_POIND;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
try {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String fileName = file.getName();
fileName = uuid + fileName;
String datePath = new DateTime().toString("yyyy/MM/dd");
fileName = datePath + "/" + fileName;
ossClient.putObject(bucketName, fileName, file);
ossClient.shutdown();
String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String uploadFile(InputStream inputStream, String fileName) {
String endpoint = ConstantPropertiesUtils.END_POIND;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
try {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
fileName = uuid + fileName;
String datePath = new DateTime().toString("yyyy/MM/dd");
fileName = datePath + "/" + fileName;
ossClient.putObject(bucketName, fileName, inputStream);
ossClient.shutdown();
String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public String uploadHtml(String html, String name) {
// 工具类获取值