【问题标题】:Convert PCM WAV to ULAW WAV in JAVA在 JAVA 中将 PCM WAV 转换为 ULAW WAV
【发布时间】:2015-08-04 15:47:16
【问题描述】:

我正在使用 Javascript/HTML5/JSF 前端和 Glassfish (Java) 后端编写基于 Web 的录音机。

我需要用 ULAW 编码保存录制的 .WAV 文件。然而,据我所知,在 HTML5/Javascript(使用getUserMedia())中录制音频的唯一方法是使用 PCM 编码。我想要一种在 ULAW 中捕获客户端录音的简单方法,但一直找不到任何方法来做到这一点。

所以现在我一直在尝试做的是:

Record in PCM wav (client side)
Upload to server using JSP
Pass the received FileItem into a JAVA converter method that returns a byte array in ULAW

我发现有人尝试在 Android 中执行此操作的以下文章:

Android PCM to Ulaw encoding wav file

但是本文引用的类要么不起作用,要么我没有正确使用它。

我目前的convertPCMtoULAW(FileItem file)Java方法:

//read the FileItem's InputStream into a byte[]
InputStream uploadedStream = file.getInputStream();
byte[] pcmBytes = new byte[(int) file.getSize()];
uploadedStream.read(pcmBytes);

//extract the number of PCM Samples from the header
int offset =40;
int length =4;
int pcmSamples = 0;
for (int i = 0; i < length; i++)
{
   pcmSamples += ((int) pcmBytes[offset+i] & 0xffL) << (8 * i);
}

//create the UlawEncoderInputStream (class in link above)
is = new UlawEncoderInputStream(
         file.getInputStream(),
         UlawEncoderInputStream.maxAbsPcm(pcmBytes, 44, pcmSamples/2)
         );

//read from the created InputStream into another byte[]
byteLength =  is.read(ulawBytes);

//I then add the ULAW header to the beginning of the byte[] 
//and pass the entire byte[] through a pre-existing Wav Verifier method
//which serializes the byte[] later on

(所有代码都编译,上面简化为包含必要的部分)

我始终只取回在变量 byteLength 中读取的 512 个字节。

我知道我正在将正确的 PCM WAV 上传到 Glassfish,因为我可以直接从 Javascript 端下载和收听我的录音。

我尝试编码后在服务器端打开文件时出现错误。

我的主要问题是:有/谁能成功使用链接页面中的类从 PCM 编码到 ULAW?

【问题讨论】:

  • 是的,我已经成功地将它用于 PCM 到 ULAW。

标签: java audio wav pcm getusermedia


【解决方案1】:

我相信您面临的问题与转码无关,而是与 Java 的 InputStream.read 的合同有关。来自documentation

从输入流中读取一些字节并将它们存储到缓冲区数组 b 中。实际读取的字节数以整数形式返回。在输入数据可用、检测到文件结尾或引发异常之前,此方法会一直阻塞。

换句话说,此函数返回的数字是在该方法的特定调用中实际读取了多少字节。合约不保证它会在流关闭之前读取所有字节,只保证在调用它时可用的字节数。

您要么必须在循环中调用其重载read(byte[] b, int off, int len),直到流关闭,要么将流包装到DataInputStream 中并使用readFully

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多