用matlab 从wav文件提取声音数据,转换为数组,给C文件使用

本文介绍使用MATLAB进行音频文件读取、十六进制数据转换及验证的方法。通过实例展示如何将音频数据转换为十六进制格式并保存至文件,再从文件中读取并转换回音频格式,最后比较转换前后音频的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

clear; 
close all; 
clc;

filename = ('stereo_sinwave.wav');
filename_h = ('hexdata.h');
%To see the contents of the file you created, use the type function:

%type hexdata.txt 

% [fname,pname]=uigetfile(filename,'Open Wave File');
% file=[pname,fname];

% % % % % % % % % % % % % % % % % % % % % % % % % %
[x,fs]=audioread(filename, 'native'); % 读入声音文件(*.wav)
whos x
x;
%x1 = x(:,1); % 抽取第 1 声道
%x2 = x(:,2); % 抽取第 2 声道
a = fi(x,1);
[m,n]=size(a);
z = a.hex; % or using z = hex(a);
z = z(1:1+20,:);

h = fopen(filename_h,'w');
%Use the fprintf function to write your data to the hexdata.txt file:
for k=1:m
    fprintf(h,'0x%s, 0x%s\r\n', hex(a(k,1)),hex(a(k,2))); %dec2hex  dec 2 hex string
end
fclose(h);

% % % % % % % % % % % verify the data 
% Ways to Import Text Files
tic
filename = ('hexdata.h');
fid = fopen(filename,'r');
lines = 0;
while ~feof(fid)
     fgetl(fid);
    lines = lines +1;
end
fclose(fid);
toc
lines
% [x2, x4] = textread(filename,'0x%s 0x%s', 'delimiter', ',', ... 
%                 'emptyvalue', NaN);
[x1,x2,x3,x4] = textread(filename,'%s %s %s %s', 'delimiter', 'x ,', ... 
                'emptyvalue', NaN);  
x2;
whos x2
x = [x1,x2,x3,x4];
whos x

y1 = hex2dec(x2); %Convert hexadecimal number string to decimal number%
y2 = hex2dec(x4);
y1 = y1/(2^8);
y2 = y2/(2^8);
[m n]= size(y1)

for k=1:m
    if(y1(k)>=uint32(2^23));
        y1(k) = y1(k) - 2^24;
    end
    if(y2(k)>=uint32(2^23));
        y2(k) = y2(k) - 2^24;
    end
end 
y1 = y1/2^23;
y2 = y2/2^23;

y3 = typecast(y1, 'double');
y4 = typecast(y2, 'double');

y5 = typecast(y1, 'int32');
y6 = typecast(y2, 'int32');

y = [y1, y2];
a = fi(y3,1);

whos str1
whos str2
whos y1
whos y2
whos y3
whos y4
whos y
y55  = y(1:1+20,:)

subplot(6,1,1);
plot(y1(1:200))
subplot(6,1,4);
plot(y2(1:200))

subplot(6,1,3);
plot(y3(1:200))
subplot(6,1,2);
plot(y4(1:200))

subplot(6,1,5);
plot(y5(1:200))
subplot(6,1,6);
plot(y6(1:200))

audiowrite('33333.wav',y,48000,'BitsPerSample',24) %存储.wav音频文件,在这里文件名为sinwave.wav
info = audioinfo('33333.wav')
0x00000000, 0x7fffff00
0x10b51500, 0x7ba37500
0x2120fb00, 0x6ed9eb00
0x30fbc500, 0x5a827900
0x40000000, 0x40000000
0x4debe400, 0x2120fb00
0x5a827900, 0x00000000
0x658c9a00, 0xdedf0400
0x6ed9eb00, 0xc0000000
0x7641af00, 0xa57d8600
0x7ba37500, 0x91261400
0x7ee7aa00, 0x845c8a00
0x7fffff00, 0x80000000
0x7ee7aa00, 0x845c8a00
0x7ba37500, 0x91261400
0x7641af00, 0xa57d8600
0x6ed9eb00, 0xc0000000
0x658c9a00, 0xdedf0400
0x5a827900, 0x00000000
0x4debe400, 0x2120fb00
0x40000000, 0x40000000

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值