import numpy as np
import soundfile as sf
def bi():
    x = np.arange(0, 48000, 1)
    y = np.sin(120./ (2 * np.pi) * x) * 0.4 + np.sin(240./ (2 * np.pi) * x) * 0.1
    return x,y

x,data = bi()

data = np.stack([data,data],axis=1)
print(data[:100].shape)

for i in range(25):
    out_wav = "result_wav/"+ str(i+1).zfill(2)+ ".wav"
    start = i*1920
    end = start + 1920
    data_select = data[start:end]
    print(start,end,out_wav,data_select.shape)
    sf.write(out_wav,
             data_select,
             22050,
             "PCM_16")

# data = data.reshape(2,-1)
# plt.scatter(x[:100],data2[:100],c='g')
# plt.scatter(x[:100],data[:100],c='r')
# plt.show()

sf.write("test.wav",
             data,
             22050,
             "PCM_16")


def wav2pcm(wav_file, pcm_file):
    f = open(wav_file, 'rb')
    f.seek(0)
    f.read(44)
    data = np.fromfile(f, dtype=np.int16)
    #data = np.concatenate([data, np.zeros(4000, dtype=np.int16)])
    data.tofile(pcm_file)

def pcm2wav(pcm_file, wav_file, channels=2, bits=16, sample_rate=48000):
    pcmf = open(pcm_file, 'rb')
    pcmdata = pcmf.read()
    pcmf.close()

    if bits % 8 != 0:
        raise ValueError("bits % 8 must == 0. now bits:" + str(bits))

    wavfile = wave.open(wav_file, 'wb')
    wavfile.setnchannels(channels)
    wavfile.setsampwidth(bits // 8)
    wavfile.setframerate(sample_rate)
    wavfile.writeframes(pcmdata)
    wavfile.close()
for i in range(25):
    out_wav = "result_wav/"+ str(i+1).zfill(2)+ ".wav"
    out_pcm = "result_pcm/"+ str(i+1).zfill(2) + ".pcm"
    wav2pcm(out_wav,out_pcm)

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注