float浮点数转音频文件wav

python将numpy.ndarray转为音频文件wav,只需要几行代码。

import soundfile as sf
sf.write("out.wav", arr, samplerate=24000) #arr为numpy.ndarray

java要是完成类似的功能就比较复杂。我把浮点数保存在了txt文件中,首先通过java读取txt并转为float[],之后转为wav,具体代码如下:

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.*;

public class test_local {
    public static void main(String[] args) throws Exception {
        String filePath = "array.txt";
        String wavPath = "out.wav";
        float[] buffer = new float[71700];
        int index = 0;
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                float value = Float.parseFloat(line);
                buffer[index++] = value;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 上面的代码仅仅是为了从txt中获取浮点数

        final byte[] byteBuffer = new byte[buffer.length * 2];
        int bufferIndex = 0;
        for (int i = 0; i < byteBuffer.length; i++) {
            final int x = (int)(buffer[bufferIndex++] * 32767.0);
            byteBuffer[i++] = (byte)x;
            byteBuffer[i] = (byte)(x >>> 8);
        }

        File out = new File(wavPath);
        final boolean bigEndian = false;
        final boolean signed = true;
        double sampleRate = 24000.0; //控制速度
        final int bits = 16;
        final int channels = 1;

        AudioFormat format = new AudioFormat((float)sampleRate, bits, channels, signed, bigEndian);
        ByteArrayInputStream bais = new ByteArrayInputStream(byteBuffer);
        AudioInputStream audioInputStream = new AudioInputStream(bais, format, buffer.length);
        AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, out);
        audioInputStream.close();
    }
}

我存浮点数的txt如下,存了71700个数:
 

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值