Java语言实现Liunx系统文字转语音,据网上资料有jacob实现的文字转语音但是只能在Windows系统上面运行,可是我们的应用服务是要部署到Liunx上运行的。所以我们不可能要单独搞一台Windows服务器。所以研究了Liunx系统的文字转语音
原理:liunx汉字TTS插件生成mp3语音文件,java读取mp3文件流返回
一共有俩种方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 第一种:基于ekho(声音好听一些) wget http: //downloads.sourceforge.net/e-guidedog/ekho-5.7.tar.xz tar Jxf ekho- 5.7 .tar.xz cd ekho- 5.7 sudo yum install libsndfile* yum install pulseaudio-libs-devel ./configure && make && make install 使用方法:ekho "我是一句话" -v Mandarin -o dd.mp3 第二种:基于espeak yum install espeak git clone cd espeak/dictsource/ espeak --compile=zh espeak "我是一句话" -w dd1.mp3 -v zh |
Java代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | @GetMapping ( "mp3" ) public ResponseEntity< byte []> getMp3( @RequestParam ( "text" ) String text){ String name = "ekho-tmp/" +System.currentTimeMillis()+ ".mp3" ; // String name = "ekho-tmp/1679022924707.mp3"; try { Process process=Runtime.getRuntime().exec( new String[]{ "/bin/sh" , "-c" , "mkdir -p ekho-tmp && ekho \"" +text+ "\" -v Mandarin -o " +name}); File file = new File(name); process.waitFor(); //为了确保执行完成在执行下面的代码 if (file.exists()){ byte [] bytes = Files.readAllBytes(file.toPath()); Files.delete(file.toPath()); return ResponseEntity.ok() .contentType(MediaType.parseMediaType( "audio/mpeg;charset=UTF-8" )) .header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "Content-Range, Last-Modified" ) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)) .body(bytes); } } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } return ResponseEntity.ok().build(); } |
本文为程序员之家原创文章,转载无需和我联系,但请注明来自程序员之家www.baldhome.com