wav转txt格式的代码实现(c,python)
时间: 2024-02-25 14:52:35 浏览: 16
以下是Python实现wav转txt格式的代码:
```python
import wave
# 打开WAV文件
wav_file = wave.open('example.wav', 'r')
# 读取WAV文件的参数
params = wav_file.getparams()
# 打开TXT文件
txt_file = open('example.txt', 'w')
# 写入TXT文件的头部信息
txt_file.write("Sample width: %d\n" % params.sampwidth)
txt_file.write("Frame rate: %d\n" % params.framerate)
txt_file.write("Channels: %d\n" % params.nchannels)
# 读取WAV文件的数据
nframes = wav_file.getnframes()
data = wav_file.readframes(nframes)
# 将数据写入TXT文件
for i in range(0, nframes):
sample = data[i]
txt_file.write("%d\n" % sample)
# 关闭文件
wav_file.close()
txt_file.close()
```
以下是C实现wav转txt格式的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>
#define BUFFER_LENGTH 2048
struct wav_header {
char chunk_id[4];
uint32_t chunk_size;
char format[4];
char subchunk1_id[4];
uint32_t subchunk1_size;
uint16_t audio_format;
uint16_t num_channels;
uint32_t sample_rate;
uint32_t byte_rate;
uint16_t block_align;
uint16_t bits_per_sample;
char subchunk2_id[4];
uint32_t subchunk2_size;
};
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s input_wav_file output_txt_file\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE *input_file = fopen(argv[1], "rb");
if (input_file == NULL) {
fprintf(stderr, "Error: failed to open input file '%s' (%s).\n", argv[1], strerror(errno));
exit(EXIT_FAILURE);
}
FILE *output_file = fopen(argv[2], "w");
if (output_file == NULL) {
fprintf(stderr, "Error: failed to open output file '%s' (%s).\n", argv[2], strerror(errno));
fclose(input_file);
exit(EXIT_FAILURE);
}
struct wav_header header;
if (fread(&header, sizeof(header), 1, input_file) != 1) {
fprintf(stderr, "Error: failed to read WAV header from input file '%s' (%s).\n", argv[1], strerror(errno));
fclose(input_file);
fclose(output_file);
exit(EXIT_FAILURE);
}
if (strncmp(header.chunk_id, "RIFF", 4) != 0 || strncmp(header.format, "WAVE", 4) != 0 ||
strncmp(header.subchunk1_id, "fmt ", 4) != 0 || strncmp(header.subchunk2_id, "data", 4) != 0) {
fprintf(stderr, "Error: input file '%s' is not a valid WAV file.\n", argv[1]);
fclose(input_file);
fclose(output_file);
exit(EXIT_FAILURE);
}
if (header.audio_format != 1 || header.bits_per_sample != 16) {
fprintf(stderr, "Error: input file '%s' has an unsupported audio format (must be PCM 16-bit).\n", argv[1]);
fclose(input_file);
fclose(output_file);
exit(EXIT_FAILURE);
}
fprintf(output_file, "Sample width: %d\n", header.bits_per_sample / 8);
fprintf(output_file, "Frame rate: %d\n", header.sample_rate);
fprintf(output_file, "Channels: %d\n", header.num_channels);
int16_t buffer[BUFFER_LENGTH];
int read_count;
while ((read_count = fread(buffer, sizeof(int16_t), BUFFER_LENGTH, input_file)) > 0) {
for (int i = 0; i < read_count; i++) {
fprintf(output_file, "%d\n", buffer[i]);
}
}
fclose(input_file);
fclose(output_file);
return 0;
}
```