WAV相关:从PCM16 Little Endian数据转WAV文件
数据格式
[0.0, -0.0, -0.0, 0.0, 0.0, 0.0, 5.960464477539063e-08, 5.960464477539063e-08, 1.1920928955078125e-07, 1.7881393432617188e-07, 2.384185791015625e-07,.....]
转换方法:c#
using System;
using System.IO;
using System.Text; namespace deserialfromPCMData
{
public static class BinaryWriterExtensions
{
private const int HeaderSize = ; private const int Hz = ; //frequency or sampling rate private const float RescaleFactor = ; //to convert float to Int16 public static void AppendWaveData<T>(this T stream, float[] buffer)
where T : Stream
{
if (stream.Length > HeaderSize)
{
stream.Seek(, SeekOrigin.End);
}
else
{
stream.SetLength(HeaderSize);
stream.Position = HeaderSize;
} // rescale
var floats = Array.ConvertAll(buffer, x => (short)(x * RescaleFactor)); // Copy to bytes
var result = new byte[floats.Length * sizeof(short)];
Buffer.BlockCopy(floats, , result, , result.Length); // write to stream
stream.Write(result, , result.Length); // Update Header
UpdateHeader(stream);
} public static void UpdateHeader(Stream stream)
{
var writer = new BinaryWriter(stream); writer.Seek(, SeekOrigin.Begin); writer.Write(Encoding.ASCII.GetBytes("RIFF")); //RIFF marker. Marks the file as a riff file. Characters are each 1 byte long.
writer.Write((int)(writer.BaseStream.Length - )); //file-size (equals file-size - 8). Size of the overall file - 8 bytes, in bytes (32-bit integer). Typically, you'd fill this in after creation.
writer.Write(Encoding.ASCII.GetBytes("WAVE")); //File Type Header. For our purposes, it always equals "WAVE".
writer.Write(Encoding.ASCII.GetBytes("fmt ")); //Mark the format section. Format chunk marker. Includes trailing null.
writer.Write(); //Length of format data. Always 16.
writer.Write((short)); //Type of format (1 is PCM, other number means compression) . 2 byte integer. Wave type PCM
writer.Write((short)); //Number of Channels - 2 byte integer
writer.Write(Hz); //Sample Rate - 32 byte integer. Sample Rate = Number of Samples per second, or Hertz.
writer.Write(Hz * * ); // sampleRate * bytesPerSample * number of channels, here 16000*2*1.
writer.Write((short)( * )); //channels * bytesPerSample, here 1 * 2 // Bytes Per Sample: 1=8 bit Mono, 2 = 8 bit Stereo or 16 bit Mono, 4 = 16 bit Stereo
writer.Write((short)); //Bits per sample (BitsPerSample * Channels) ?? should be 8???
writer.Write(Encoding.ASCII.GetBytes("data")); //"data" chunk header. Marks the beginning of the data section.
writer.Write((int)(writer.BaseStream.Length - HeaderSize)); //Size of the data section. data-size (equals file-size - 44). or NumSamples * NumChannels * bytesPerSample ??
}
} //end of class
}
using System;
using System.IO;
using System.Text; namespace deserialfromPCMData
{
class SaveAudioStreamToWav
{
static void Main(string[] args)
{ Stream instream = File.OpenRead(@"g:\sample.txt"); BufferedStream bfs = new BufferedStream(instream);
byte[] array = new byte[bfs.Length];
instream.Read(array, , array.Length); string str = Encoding.Default.GetString(array); var StreamSample = str.Substring(, str.Length - ).Split(','); var floatsArray = new float[StreamSample.Length];
floatsArray = Array.ConvertAll(StreamSample, x => (float)Convert.ToDouble(x)); using (var stream = new FileStream(@"g:\sample2.wav", FileMode.Create, FileAccess.ReadWrite))
{
stream.AppendWaveData(floatsArray);
}
}
}
}
Java方法:
package com; import com.sun.media.sound.WaveFileWriter;
import org.junit.Test; import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import java.io.*;
import java.util.Arrays; //https://stackoverflow.com/questions/3599378/java-read-wav-file-as-a-float-array
//
//https://stackoverflow.com/questions/26824663/how-do-i-use-audio-sample-data-from-java-sound
//
//https://stackoverflow.com/questions/4440015/java-pcm-to-wav
public class TestWavFile { //采样率16kHz
private float SAMPLING_RATE = 16000;
private float sampleSizeBits = 16; //把short(2字节)拆解成字节流byte[2]
public byte[] get16BitPcm(short[] data) { byte[] resultData = new byte[2 * data.length];
int iter = 0;
for (short sample : data) {
resultData[iter++] = (byte)(sample & 0x00ff);
resultData[iter++] = (byte)((sample & 0xff00) >>> 8);
}
return resultData;
} @Test
public void test() throws IOException{ BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(
new FileInputStream("g:/sample.txt"))); StringBuffer buffer = new StringBuffer();
String line = null; while ( (line = bufferedReader.readLine()) != null)
{
buffer.append(line);
} int len = buffer.length(); String raw = buffer.substring(1,len-1); Short[] data = Arrays.stream(raw.split(","))
.map(track->( Float.valueOf(track) * 0x7fff ))
.map(item->item.shortValue()).toArray(Short[]::new); short [] frameData = new short[data.length]; for (int i = 0; i< data.length; i++) {
frameData[i] = data[i];
} WaveFileWriter writer = new WaveFileWriter(); FileOutputStream outStream = new FileOutputStream("g:/sample.wav");
//(采样率,比特位,通道,是否有符号,大小端)
//比特位:short 2个字节 2*8 = 16
//是否有符号:是否有负数
//
AudioFormat format = new AudioFormat(SAMPLING_RATE,16,1,true,false); AudioInputStream audioInputStream = new AudioInputStream(new ByteArrayInputStream(get16BitPcm(frameData)), format, frameData.length); writer.write(audioInputStream, AudioFileFormat.Type.WAVE, outStream); }
}
java封装工具:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.media.sound.WaveFileWriter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils; import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays; @Slf4j
public final class WavFileGenerator { //采样率16kHz
private float SAMPLING_RATE = 16000;
private float sampleSizeBits = 16; private int HeaderSize = 44; //frequency or sampling rate
private int Hz = 16_000; private byte[] values; public WavFileGenerator(String ctx)
{
this(convert(ctx));
}
public WavFileGenerator(String []values)
{
convert(toPrimitive(Arrays.asList(values).stream().map(Float::valueOf).toArray(size -> new Float[size])));
} public WavFileGenerator(short[] values)
{
/*sizeof(short) was 2 bytes in java platform*/
byte[] result = new byte[values.length * 2]; // 1short = 2bytes
int iter = 0;
for (short sample : values) {
result[iter++] = (byte)(sample & 0x00ff);
result[iter++] = (byte)((sample & 0xff00) >>> 8);
} this.values = result;
}
public WavFileGenerator(float[] floatValues)
{
this(convert(floatValues));
} static float[] toPrimitive(Float[] floats)
{
return ArrayUtils.toPrimitive(floats);
} public static final short[] convert(float[] values)
{
//PCM 16bit little endian
short[] shortValues = new short[values.length];
for (int i = 0; i < values.length; i++) {
float value = values[i];
shortValues[i] = (short) (value < 0 ? value* 0x8000 : value*0x7fff);
}
return shortValues;
} public static final float[] convert(String ctx)
{
ObjectMapper objectMapper = new ObjectMapper();
try {
Float[] data = objectMapper.readValue(ctx, Float[].class);
return toPrimitive(data);
} catch (IOException e) {
log.error("转换出错:{}",e);
}
return new float[0];
} public byte[] getFmtChunk()
{
return null;
} public byte[] getDataChunk()
{
return values;
} void builder()
{ } public ByteBuffer getAudioStream()
{
return null;
} public void saveFile(String dest) throws IOException { WaveFileWriter writer = new WaveFileWriter();
FileOutputStream outStream = new FileOutputStream(dest);
AudioFormat format = new AudioFormat(SAMPLING_RATE,16,1,true,false);
int frames = values.length / 2;
AudioInputStream audioInputStream = new AudioInputStream(new ByteArrayInputStream(values), format, frames);
writer.write(audioInputStream, AudioFileFormat.Type.WAVE, outStream);
audioInputStream.close();
outStream.close();
}
}
运行以上两个文件,最终会成功wav文件。
WAV相关:从PCM16 Little Endian数据转WAV文件的更多相关文章
- 【应用】:shell crontab定时生成oracle表的数据到txt文件,并上传到ftp
一.本人环境描述 1.oracle服务端装在win7 32位上,oracle版本为10.2.0.1.0 2.Linux为centos6.5 32位,安装在Oracle VM Vir ...
- HTML5操作麦克风获取音频数据(WAV)的一些基础技能
基于HTML5的新特性,操作其实思路很简单. 首先通过navigator获取设备,然后通过设备监听语音数据,进行原始数据采集. 相关的案例比较多,最典型的就是链接:https://developer. ...
- pcm数据生成wav文件
Qt由pcm数据生成wav文件 void AudioGrabber::saveWave(const QString &fileName, const QByteArray &raw, ...
- C#中使用WavHelper保存录音数据为wav文件
C#将录音数据文件保存为wav格式文件,这里使用到的是WavHelper工具类. WavHelper工具类: using System; using System.Collections.Generi ...
- php添加数据到xml文件的例子
php添加数据到xml文件中 时间:2015-12-17 06:30:37来源:网络 导读:php添加数据到xml文件中 xml文件:stu.xml: 复制代码代码如下: <?xml ver ...
- MYSQL数据库导入大数据量sql文件失败的解决方案
1.在讨论这个问题之前首先介绍一下什么是"大数据量sql文件". 导出sql文件.选择数据库-----右击选择"转储SQL文件"-----选择"结构和 ...
- [大数据]-Fscrawler导入文件(txt,html,pdf,worf...)到Elasticsearch5.3.1并配置同义词过滤
fscrawler是ES的一个文件导入插件,只需要简单的配置就可以实现将本地文件系统的文件导入到ES中进行检索,同时支持丰富的文件格式(txt.pdf,html,word...)等等.下面详细介绍下f ...
- Python:将爬取的网页数据写入Excel文件中
Python:将爬取的网页数据写入Excel文件中 通过网络爬虫爬取信息后,我们一般是将内容存入txt文件或者数据库中,也可以写入Excel文件中,这里介绍关于使用Excel文件保存爬取到的网页数据的 ...
- 30G 上亿数据的超大文件,如何快速导入生产环境?
Hello,大家好,我是楼下小黑哥~ 如果给你一个包含一亿行数据的超大文件,让你在一周之内将数据转化导入生产数据库,你会如何操作? 上面的问题其实是小黑哥前段时间接到一个真实的业务需求,将一个老系统历 ...
随机推荐
- C++中得sort函数的比较函数(第三个参数)为什么要声明为static
sort中的比较函数compare要声明为静态成员函数或全局函数,不能作为普通成员函数,否则会报错. 因为:非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中 ...
- kafka2.12 集群搭建
前提: 1.下载 kafka http://kafka.apache.org/downloads 2.下载配置zookeeper http://www.cnblogs.com/eggplantpro/ ...
- CSP-J总结&题解
总结: 这一次,最后一次,还是不行啊. 文件操作方面:没有FCLOSE,血的教训. 考场复盘: 首先一二题没什么好讲的,秒切.但是第三题由于一开始看出来是完全背包,但是好像又不是,去年又有摆渡车阴影, ...
- 博客系统的使用(typecho、WordPress等等)
一.下载,解压,安装 二.Apache配置虚拟主机,(host文件修改) 三.开启php.ini中pdo类型的扩展适配数据库 四.按照指示页面配置 五.操作控制面板和blog前台
- SB的SDOISB记
恩, SDOI考完 考完. day0 : 上车时看myj费劲跨过行李的样子,嘲讽他腿短.很happy 吃饭时和myj吃了羊肉..汤 虽然贵, 但是意外的好吃 继续嘲讽myj不是男人,吃的少 不知怎么的 ...
- Ibatis自动解决sql注入机制
疑问1:为什么IBatis解决了大部分的sql注入?(实际上还有部分sql语句需要关心sql注入,比如like) 之前写Java web,一直使用IBatis,从来没有考虑过sql注入:最近写php( ...
- UK Biobank专题
这个时代的生信,统计遗传,不懂或不会用这个数据库就说不过去了. 看看10年GWAS里是如何定位和评价UK biobank的: For the near future, the UK Biobank i ...
- HTMLPage测试js通过ajax调用
HTMLPage测试js通过ajax调用接口 <!DOCTYPE html> <html lang="en" xmlns="http://www.w3. ...
- 降维算法整理--- PCA、KPCA、LDA、MDS、LLE 等
转自github: https://github.com/heucoder/dimensionality_reduction_alo_codes 网上关于各种降维算法的资料参差不齐,同时大部分不提供源 ...
- Flutter -------- 加载本地图片资源和网络图片
在Flutter加载本地图片资源 在Flutter项目目录下创建文件夹 images ,在文件夹中添加几张图片 指定资源 pubspec.yaml文件中 version: 1.0.0+1 enviro ...