www.gusucode.com > gui 界面实现语音信号简单分析matlab源码程序 > 语音信号分析/voiceLevelGUI.m

    function varargout = voiceLevelGUI(varargin)
% VOICELEVELGUI M-file for voiceLevelGUI.fig
%      VOICELEVELGUI, by itself, creates a new VOICELEVELGUI or raises the existing
%      singleton*.
%
%      H = VOICELEVELGUI returns the handle to a new VOICELEVELGUI or the handle to
%      the existing singleton*.
%
%      VOICELEVELGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in VOICELEVELGUI.M with the given input arguments.
%
%      VOICELEVELGUI('Property','Value',...) creates a new VOICELEVELGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before voiceLevelGUI_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to voiceLevelGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Copyright 2002-2003 The MathWorks, Inc.

% Edit the above text to modify the response to help voiceLevelGUI

% Last Modified by GUIDE v2.5 29-May-2005 21:31:22

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @voiceLevelGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @voiceLevelGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before voiceLevelGUI is made visible.
function voiceLevelGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to voiceLevelGUI (see VARARGIN)

% Choose default command line output for voiceLevelGUI
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes voiceLevelGUI wait for user response (see UIRESUME)
% uiwait(handles.voiceLevelGUI);

% 坐标轴初始化
axes(handles.axes1);
xlabel('Sample');
ylabel('Analog Input (Volts)');
title('Analog Data Acquisition');

axes(handles.axes2);
hxlabel = xlabel('Frequency (Hz)');
hylabel = ylabel('Magnitude (dB)');

axes(handles.axesL1);
ylabel('Magnitude(dB)');

axes(handles.axesLL1);
ylabel('Magnitude(dB)');

%% 初始化appdata
setappdata(handles.voiceLevelGUI,'BandData',[]);
setappdata(handles.voiceLevelGUI,'Band2Data',[]);

% 日期时间显示
set(handles.timestr,'string',datestr(now,0));
htimer = timer('StartDelay',1,'TimerFcn',...
    'htimestr=findall(0,''tag'',''timestr'');set(htimestr,''string'',datestr(now,0));',...
    'Period',1,'ExecutionMode','fixedSpacing','tag','showtime');
start(htimer);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 可以在这里写入一些初始化操作
% 我这里以前写的是身份验证的一个小的加密的程序段
% sn
filename=matlabroot;
filename=[filename,'\voiceLevelGUIsn.bin'];
if(exist(filename)==0)
    fid=fopen(filename,'w+');
    fileattrib(filename,'+h');
    sn=[0,1];
    fwrite(fid,sn,'integer*4');
    fclose(fid);
else
    fid=fopen(filename,'r');
    sn=fread(fid,2,'int32');
    fclose(fid);
    if(sn(1)==0)
        num=sn(2)+1;
        sn(2)=num;
        if(num>5)
            answer=inputdlg('请输入注册号:','Please enter your SN');
            if(~isempty(answer))
                str=answer{1};
                snn=str2num(str);
                if snn==987656789
                    sn(1)=1;
                    fileattrib(filename,'-h');
                    fid=fopen(filename,'w');
                    fwrite(fid,sn,'integer*4');
                    fclose(fid);
                    fileattrib(filename,'+h');
                else
                    uiwait(msgbox('输入的注册号不正确!','注册号出错','error','modal'));
                    set(handles.btnRun,'Enable','off');
                end
            else
                uiwait(msgbox('输入的注册号不正确!','注册号出错','error','modal'));
                set(handles.btnRun,'Enable','off');
            end
        else
            fileattrib(filename,'-h');
            fid=fopen(filename,'w');
            fwrite(fid,sn,'integer*4');
            fclose(fid);
            fileattrib(filename,'+h');
        end
    end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% --- Outputs from this function are returned to the command line.
function varargout = voiceLevelGUI_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function voiceLevelGUI_WindowButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to voiceLevelGUI (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% get(gcf,'position');


% --- Executes during object creation, after setting all properties.
function editSamplesPerT_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editSamplesPerT (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function editSampleR_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editSampleR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function editTimerPeriod_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editTimerPeriod (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function editChan_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editChan (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function editId_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editId (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function editL1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editL1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function editL2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editL2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function editL3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editL3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes during object creation, after setting all properties.
function editL4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editL4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes during object creation, after setting all properties.
function editL5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editL5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end




% --- Executes during object creation, after setting all properties.
function editLL1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editLL1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes during object creation, after setting all properties.
function editLL2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editLL2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes during object creation, after setting all properties.
function editLL3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editLL3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes during object creation, after setting all properties.
function editLL4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editLL4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end




% --- Executes during object creation, after setting all properties.
function editLL5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editLL5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes during object creation, after setting all properties.
function editALevel_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editALevel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function editSampleR_Callback(hObject, eventdata, handles)
% hObject    handle to editSampleR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editSampleR as text
%        str2double(get(hObject,'String')) returns contents of editSampleR as a double
str = get(hObject,'string');
data = str2num(str);
if isempty(data)||data<8000||data>44100||round(data)~=data  % 输入参数有效性检测
    errordlg('输入必须为8000到44100之间的整数值!','参数错误');
    set(hObject,'BackgroundColor','r');
else
    set(hObject,'BackgroundColor','w');
    set(hObject,'UserData',data);
end



function editSamplesPerT_Callback(hObject, eventdata, handles)
% hObject    handle to editSamplesPerT (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editSamplesPerT as text
%        str2double(get(hObject,'String')) returns contents of editSamplesPerT as a double
str = get(hObject,'string');
data = str2num(str);
if isempty(data)||data<=0||round(data)~=data  % 输入参数有效性检测
    errordlg('输入必须为大于0的整数值!','参数错误');
    set(hObject,'BackgroundColor','r');
else
    set(hObject,'BackgroundColor','w');
    set(hObject,'UserData',data);
end



function editTimerPeriod_Callback(hObject, eventdata, handles)
% hObject    handle to editTimerPeriod (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editTimerPeriod as text
%        str2double(get(hObject,'String')) returns contents of editTimerPeriod as a double
str = get(hObject,'string');
data = str2num(str);
if isempty(data)||data<=0  % 输入参数有效性检测
    errordlg('输入必须为大于0的数值!','参数错误');
    set(hObject,'BackgroundColor','r');
else
    set(hObject,'BackgroundColor','w');
    set(hObject,'UserData',data);
end


function editChan_Callback(hObject, eventdata, handles)
% hObject    handle to editChan (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editChan as text
%        str2double(get(hObject,'String')) returns contents of editChan as a double
str = get(hObject,'string');
data = str2num(str);
if isempty(data)||data<0||round(data)~=data||length(data)>1  % 输入参数有效性检测
    errordlg('输入必须为1个不小于0的整数值!','参数错误');
    set(hObject,'BackgroundColor','r');
else
    set(hObject,'BackgroundColor','w');
    set(hObject,'UserData',data);
end



function editId_Callback(hObject, eventdata, handles)
% hObject    handle to editId (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editId as text
%        str2double(get(hObject,'String')) returns contents of editId as a double
str = get(hObject,'string');
data = str2num(str);
if isempty(data)||data<0||round(data)~=data  % 输入参数有效性检测
    errordlg('输入必须为不小于0的整数值!','参数错误');
    set(hObject,'BackgroundColor','r');
else
    set(hObject,'BackgroundColor','w');
    set(hObject,'UserData',data);
end



% --- Executes on button press in btnRun.
function btnRun_Callback(hObject, eventdata, handles)
% hObject    handle to btnRun (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
str = get(hObject,'string');
flag = get(hObject,'UserData');
if strcmp(str,'Run')    % 如果尚未运行或已经停止
    if flag % 如果是暂停
        try
            start(handles.ai);
            set(hObject,'string','Stop');
            return;
        catch
            errStr = lasterr;
            errordlg(errStr,'Error...');
        end
    end
    % 获取设置的参数
    deviceId = get(handles.editId,'UserData');
    hwChan = get(handles.editChan,'UserData');
    sampleR = get(handles.editSampleR,'UserData');
    samplesPerT = get(handles.editSamplesPerT,'UserData');
    timerPeriod = get(handles.editTimerPeriod,'UserData');
    try
        set(handles.voiceLevelGUI,'pointer','watch'); % 设置鼠标为等待态
        % 创建两个曲线句柄
        axes(handles.axes1);  cla
        hline1 = line('xdata',[0 0.01],'ydata',[0,1e-6],'visible','off');
        axes(handles.axes2);  cla
        axis([0 1 0 1]);
        hline2 = line('xdata',[0 0.01],'ydata',[0,1e-6],'visible','off');
        %%
        % 创建patch
        % 倍频程
        axes(handles.axesL1);
        line([0 1],[0 0],'color','r');
        patchL1 = patch([0 1 1 0],[0 0 0 0],'b');
        axes(handles.axesL2);
        line([0 1],[0 0],'color','r');
        patchL2 = patch([0 1 1 0],[0 0 0 0],'b');
        axes(handles.axesL3);
        line([0 1],[0 0],'color','r');
        patchL3 = patch([0 1 1 0],[0 0 0 0],'b');
         axes(handles.axesL4);
        line([0 1],[0 0],'color','r');
        patchL4 = patch([0 1 1 0],[0 0 0 0],'b');
        axes(handles.axesL5);
        line([0 1],[0 0],'color','r');
        patchL5 = patch([0 1 1 0],[0 0 0 0],'b');
        
        % 1/3倍频程
        axes(handles.axesLL1);
        line([0 1],[0 0],'color','r');
        patchLL1 = patch([0 1 1 0],[0 0 0 0],'b');
        axes(handles.axesLL2);
        line([0 1],[0 0],'color','r');
        patchLL2 = patch([0 1 1 0],[0 0 0 0],'b');
        axes(handles.axesLL3);
        line([0 1],[0 0],'color','r');
        patchLL3 = patch([0 1 1 0],[0 0 0 0],'b');
         axes(handles.axesLL4);
        line([0 1],[0 0],'color','r');
        patchLL4 = patch([0 1 1 0],[0 0 0 0],'b');
        axes(handles.axesLL5);
        line([0 1],[0 0],'color','r');
        patchLL5 = patch([0 1 1 0],[0 0 0 0],'b');
        
        % 存储对象与guidata
        handles.line1 = hline1;
        handles.line2 = hline2;
        handles.patchL1 = patchL1;
        handles.patchL2 = patchL2;
        handles.patchL3 = patchL3;
        handles.patchL4 = patchL4;
        handles.patchL5 = patchL5;
        handles.patchLL1 = patchLL1;
        handles.patchLL2 = patchLL2;
        handles.patchLL3 = patchLL3;
        handles.patchLL4 = patchLL4;
        handles.patchLL5 = patchLL5;

        guidata(gcf,handles);
        %% 
        % 创建并配置object
        ai = analoginput('winsound',deviceId);
        addchannel(ai,hwChan);
        actrualSampleR = setverify(ai,'SampleRate',sampleR);
        set(handles.editSampleR,'string',actrualSampleR);
        set(ai,'SamplesPerTrigger',samplesPerT);
        set(ai,'TriggerRepeat',1);
        set(ai,'TriggerType','manual');
        set(ai,'TimerPeriod',timerPeriod);
        set(ai,'TimerFcn',{@localfftShowData,handles}); % pass addtional paras
%         set(ai,'SamplesAcquiredFcn',{@saveData,handles});
        start(ai);  % Start the analog input object.
        trigger(ai);
        handles.ai = ai;
        guidata(gcf,handles);
        %%
        % 界面状态更新
        set(handles.btnExport,'UserData',[]);
        set(hObject,'string','Stop');
        set(handles.editId,'enable','off');
        set(handles.editChan,'enable','off');
        set(handles.editSampleR,'enable','off');
        set(handles.editSamplesPerT,'enable','off');
        set(handles.editTimerPeriod,'enable','off');
        set(handles.btnReset,'enable','off');
        set(handles.voiceLevelGUI,'pointer','arrow'); % 设置鼠标为正常态
    catch
        errStr = lasterr;
        errordlg(errStr,'Error...');
        set(handles.voiceLevelGUI,'pointer','arrow'); % 设置鼠标为正常态
    end
else    % 如果已经运行
    stop(handles.ai);
    % 将轴上现有数据保存在轴的userdata中备用
    xresult = get(handles.line1,'ydata');
    set(handles.axes1,'UserData',xresult);
    xresult = get(handles.line2,'xdata');
    yresult = get(handles.line2,'ydata');
    set(handles.axes1,'UserData',[xresult(:),yresult(:)]);
    % 更新界面
    set(hObject,'UserData',1);
    set(hObject,'string','Run');
    set(handles.btnReset,'enable','on');
end


% --- Executes on button press in btnHelp.
function btnHelp_Callback(hObject, eventdata, handles)
% hObject    handle to btnHelp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% msgstr = 'Sorry,it doesn''t finish yet!';
% msgbox(msgstr,'Sorry...');
!voiceLevelHelp.CHM  

% --- Executes on button press in btnExport.
function btnExport_Callback(hObject, eventdata, handles)
% hObject    handle to btnExport (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% 获取待保存的数据
BandData = getappdata(handles.voiceLevelGUI,'BandData');
Band2Data = getappdata(handles.voiceLevelGUI,'Band2Data');
LaLevel = get(handles.editALevel,'UserData');

result.BandData = BandData;
result.Band2Data = Band2Data;
result.LaLevel = LaLevel;

ButtonName=questdlg('保存结果为何种形式?', ...
    '测量结果保存', ...
    'TXT文件','MAT文件','取消','MAT文件');
switch ButtonName,
    case 'MAT文件',
        [fname,path] = uiputfile('*.mat','保存为');
        if path==0  % 取消文件保存操作
            return;
        end
        save([path fname],'result','-v6'); % 保存为低版本也可以用的mat文件
    case 'TXT文件',
        [fname,pathname] = uiputfile('*.txt','保存为');
        if pathname==0  % 取消文件保存操作
            return;
        end
        [pathstr,filename]=fileparts(fname);
        fid = fopen([pathname filename,'.txt'],'w');
        fprintf(fid,'\r\n%%=================%s=================\r\n',datestr(now,0));
        fprintf(fid,'\r\n倍频程声级\r\n');
        fprintf(fid,'%%%8.4f %8.4f %8.4f %8.4f %8.4f\r\n',31.5,63,125,250,500);
        fprintf(fid,'%8.6f %8.6f %8.6f %8.6f %8.6f\r\n',BandData);
        fprintf(fid,'\r\n');
        fprintf(fid,'%%三分之一倍频程声级\r\n');
        fprintf(fid,'%%%8.4f %8.4f %8.4f %8.4f %8.4f\r\n',50,100,200,400,800);
        fprintf(fid,'%8.6f %8.6f %8.6f %8.6f %8.6f\r\n',Band2Data);
%         fprintf(fid,'\r\n');
        fprintf(fid,'\r\n%% A声级\r\n');
        fprintf(fid,'%8.6f\r\n',LaLevel);
        fclose(fid);

    case '取消',
        return;
end % switch



% --- Executes on button press in btnReset.
function btnReset_Callback(hObject, eventdata, handles)
% hObject    handle to btnReset (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

set(handles.editId,'enable','on');
set(handles.editChan,'enable','on');
set(handles.editSampleR,'enable','on');
set(handles.editSamplesPerT,'enable','on');
set(handles.editTimerPeriod,'enable','on');
set(handles.editId,'string',num2str(0),'UserData',0);
set(handles.editChan,'string',num2str(1),'UserData',1);
set(handles.editSampleR,'string',num2str(8000),'UserData',8000);
set(handles.editSamplesPerT,'string',num2str(1024),'UserData',1024);
set(handles.editTimerPeriod,'string',num2str(0.2),'UserData',0.2);
set(handles.btnRun,'UserData',0);



% --- Executes on button press in btnExit.
function btnExit_Callback(hObject, eventdata, handles)
% hObject    handle to btnExit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
selection = questdlg(['退出 ' get(handles.voiceLevelGUI,'Name') '?'],...
    ['退出 ...'],...
    '是','否','是');
if strcmp(selection,'否')
    return;
end
htimer = timerfind('tag','showtime');
stop(htimer);
delete(htimer);
try
    if isvalid(handles.ai)
        if strcmp(get(handles.ai, 'Running'), 'On')
            stop(handles.ai);
        end
        delete(handles.ai);
    end
catch
    
end

delete(handles.voiceLevelGUI);




%% ************************************************************************
function localfftShowData(obj, event, handles)
%%
% Get the handles of those objects.
haxes1 = handles.axes1;
haxes2 = handles.axes2;
hLine1 = handles.line1;
hLine2 = handles.line2;

% 倍程频相关对象
hBand1edit = handles.editL1;
hBand2edit = handles.editL2;
hBand3edit = handles.editL3;
hBand4edit = handles.editL4;
hBand5edit = handles.editL5;
hBand1axes = handles.axesL1;
hBand2axes = handles.axesL2;
hBand3axes = handles.axesL3;
hBand4axes = handles.axesL4;
hBand5axes = handles.axesL5;
hBand1patch = handles.patchL1;
hBand2patch = handles.patchL2;
hBand3patch = handles.patchL3;
hBand4patch = handles.patchL4;
hBand5patch = handles.patchL5;

% 1/3倍程频相关对象
hBand21edit = handles.editLL1;
hBand22edit = handles.editLL2;
hBand23edit = handles.editLL3;
hBand24edit = handles.editLL4;
hBand25edit = handles.editLL5;
hBand21axes = handles.axesLL1;
hBand22axes = handles.axesLL2;
hBand23axes = handles.axesLL3;
hBand24axes = handles.axesLL4;
hBand25axes = handles.axesLL5;
hBand21patch = handles.patchLL1;
hBand22patch = handles.patchLL2;
hBand23patch = handles.patchLL3;
hBand24patch = handles.patchLL4;
hBand25patch = handles.patchLL5;


set(hLine1,'visible','on');
set(hLine2,'visible','on');
%%
% Obtain the available time and data.
blockSize = get(obj,'SamplesPerTrigger');
x = peekdata(obj,blockSize);
%%
% FFT calculation.
Fs = obj.SampleRate;
[firstcross, lastcross] = localDaqCrossPt(x);
fftx = x(firstcross:lastcross);
blockSize = length(fftx);
[f,mag] = localDaqfft(fftx,Fs,blockSize);


%%
% Dynamically modify Analog axis as we go.
maxX=max(x);
minX=min(x);
yax1=get(haxes1,'YLim');
if minX<yax1(1),
    yax1(1)=minX;
end
if maxX>yax1(2),
    yax1(2)=maxX;
end
set(haxes1,'YLim',yax1,'XLim',[0 length(x)]);
%%
% Dynamically modify Frequency axis as we go.
maxF=max(f);
minF=min(f);
xax=get(haxes2,'XLim');
if minF<xax(1),
    xax(1)=minF;
end
if maxF>xax(2),
    xax(2)=floor(maxF/2);
end
set(haxes2,'XLim',xax);
%%
% Dynamically modify Magnitude axis as we go.
maxM=max(mag);
minM=min(mag);
yax2=get(haxes2,'YLim');
if minM<yax2(1),
    yax2(1)=minM;
end
if maxM>yax2(2),
    yax2(2)=maxM;
end
set(haxes2,'YLim',yax2);

%% 更新左边的轴上曲线
set(hLine1, 'YData', x(:,1),'XData',1:length(x));
fHalf = f(1:floor(end/2),:); magHalf = mag(1:floor(end/2),:);
set(hLine2, 'XData', fHalf(:,1), 'YData', magHalf(:,1));

%%
% 计算倍频程
index1 = (f>22.5&f<45);
if sum(index1) >0
    band1val = mean(mag(index1));
else
    band1val = 0;   % 没有该频率段的值
end
index2 = (f>45&f<90);
if sum(index2) >0
    band2val = mean(mag(index2));
else
    band2val = 0;   % 没有该频率段的值
end
index3 = (f>90&f<180);
if sum(index3) >0
    band3val = mean(mag(index3));
else
    band3val = 0;   % 没有该频率段的值
end
index4 = (f>180&f<354);
if sum(index4) >0
    band4val = mean(mag(index4));
else
    band4val = 0;   % 没有该频率段的值
end
index5 = (f>354&f<707);
if sum(index5) >0
    band5val = mean(mag(index5));
else
    band5val = 0;   % 没有该频率段的值
end

% 计算1/3倍频程
index1 = (f>44.5&f<56); % 50
if sum(index1) >0
    band21val = mean(mag(index1));
else
    band21val = 0;   % 没有该频率段的值
end
index2 = (f>89&f<112); % 100
if sum(index2) >0
    band22val = mean(mag(index2));
else
    band22val = 0;   % 没有该频率段的值
end
index3 = (f>178&f<224); % 200
if sum(index3) >0
    band23val = mean(mag(index3));
else
    band23val = 0;   % 没有该频率段的值
end
index4 = (f>356&f<448); % 400
if sum(index4) >0
    band24val = mean(mag(index4));
else
    band24val = 0;   % 没有该频率段的值
end
index5 = (f>712&f<896); % 800
if sum(index5) >0
    band25val = mean(mag(index5));
else
    band25val = 0;   % 没有该频率段的值
end

%%
% 计算A声级
deletaI = [-70.4 -63.4 -56.7 -50.5 -44.7 -39.4 -34.6 -30.2 -26.2 -22.5,...
    -19.1 -16.1 -13.4 -10.9 -8.6 -6.6 -4.8 -3.2 -1.9 -0.8 0 0.6 1.0 1.2 1.3];
ffI = [10 12.5 16 20 25 31.5 40 50 63 80 100 125 160 200 250 315 400 500,...
    630 800 1000 1250  1600 2000 2500];
sumTmp = 0;
for k = 1:length(ffI)
    indx = f>(ffI(k)-0.5)&f<(ffI(k)+0.5);  % 查找频率为给定的那25个值的序号
    % 容许偏差为0.5,个人认为你在这里的理解有问题,如果按照你的意思,此处直接
    % 用f ==ffI(k),估计计算出来的值基本上都是0;我这样处理也应该不对的,
    Lpi = mag(indx);
    sumTmp = sumTmp+ 10.^((sum(Lpi)+deletaI(k))/10);
end
if abs(sumTmp) <1e-9 % 避免为sumTmp为0的情况
    sumTmp = 1e-9;
end
La = 10*log10(sumTmp);
set(handles.editALevel,'string',num2str(La,6));

% 保存La数据于UserData,供导出时用
LaData = get(handles.editALevel,'UserData');
LaData = [LaData;La];
set(handles.editALevel,'UserData',LaData);

% 保存倍频程数据于appdata供导出时用
BandData = getappdata(handles.voiceLevelGUI,'BandData');
tmpData = [band1val,band2val,band3val,band4val,band5val];
BandData = [BandData;tmpData];
setappdata(handles.voiceLevelGUI,'BandData',BandData);
% 保存1/3倍频程数据于appdata供导出时用
Band2Data = getappdata(handles.voiceLevelGUI,'Band2Data');
tmpData = [band21val,band22val,band23val,band24val,band25val];
Band2Data = [Band2Data;tmpData];
setappdata(handles.voiceLevelGUI,'Band2Data',Band2Data);


%%
% 动态更新倍频程显示的坐标
yax3 = get(hBand1axes,'YLim');
upYlim = max([band1val,band2val,band3val,band4val,band5val]);
lowYlim = min([band1val,band2val,band3val,band4val,band5val]);
if upYlim > yax3(end)
    yax3(end) = yax3(end)+10;
end
if lowYlim <  yax3(1)
     yax3(1) = yax3(1)-10;
end
set(hBand1axes,'Ylim',yax3);
set(hBand2axes,'Ylim',yax3);
set(hBand3axes,'Ylim',yax3);
set(hBand4axes,'Ylim',yax3);
set(hBand5axes,'Ylim',yax3);

 %%
% Update the plots.
low = yax3(1);
set(hBand1edit,'string',num2str(band1val,4));
set(hBand2edit,'string',num2str(band2val,4));
set(hBand3edit,'string',num2str(band3val,4));
set(hBand4edit,'string',num2str(band4val,4));
set(hBand5edit,'string',num2str(band5val,4));

set(hBand1patch,'YData',[low low band1val band1val]);
set(hBand2patch,'YData',[low low band2val band2val]);
set(hBand3patch,'YData',[low low band3val band3val]);
set(hBand4patch,'YData',[low low band4val band4val]);
set(hBand5patch,'YData',[low low band5val band5val]);

%%
% 动态更新1/3倍频程显示的坐标
yax23 = get(hBand21axes,'YLim');
upYlim2 = max([band21val,band22val,band23val,band24val,band25val]);
lowYlim2 = min([band21val,band22val,band23val,band24val,band25val]);
if upYlim2 > yax23(end)
    yax23(end) = yax3(end)+10;
end
if lowYlim2 <  yax23(1)
     yax23(1) = yax23(1)-10;
end
set(hBand21axes,'Ylim',yax23);
set(hBand22axes,'Ylim',yax23);
set(hBand23axes,'Ylim',yax23);
set(hBand24axes,'Ylim',yax23);
set(hBand25axes,'Ylim',yax23);

 %%
% Update the plots.
low2 = yax23(1);
set(hBand21edit,'string',num2str(band21val,4));
set(hBand22edit,'string',num2str(band22val,4));
set(hBand23edit,'string',num2str(band23val,4));
set(hBand24edit,'string',num2str(band24val,4));
set(hBand25edit,'string',num2str(band25val,4));

set(hBand21patch,'YData',[low2 low2 band21val band21val]);
set(hBand22patch,'YData',[low2 low2 band22val band22val]);
set(hBand23patch,'YData',[low2 low2 band23val band23val]);
set(hBand24patch,'YData',[low2 low2 band24val band24val]);
set(hBand25patch,'YData',[low2 low2 band25val band25val]);

drawnow;




%%  ***********************************************************************
function [firstcross, lastcross] = localDaqCrossPt(data)
% Calculate the first & last crosspoints over the mean of the data.
% function returns 0 if no crosspoint is found.
firstcross = 0;
crossvalue = mean(data);
for i = 2:length(data)
    if(data(i-1) >= crossvalue & data(i) < crossvalue)
        firstcross = i;
        break;
    end
end

lastcross = 0;
for i = length(data):-1:2
    if(data(i-1) >= crossvalue & data(i) < crossvalue)
        lastcross = i;
        break;
    end
end




%% ***********************************************************************  
% Calculate the fft of the data.
function [f, mag] = localDaqfft(data,Fs,blockSize)
%%
% Calculate the fft of the data.
xFFT = fft(data);
xfft = abs(xFFT);
%%
% Avoid taking the log of 0.
index = find(xfft == 0);
xfft(index) = 1e-17;

mag = 20*log10(xfft);
mag = mag(1:floor(blockSize/2));

f = (0:length(mag)-1)*Fs/blockSize;
f = f(:);

% 理解错误,原来SamplesAcquiredFcn只执行一次
% function saveData(obj,event,handles)
% data = getdata(obj);
% allData = get(handles.btnExport,'UserData');
% allData = [allData;data];
% set(handles.btnExport,'UserData');
%