2013-05-17 873 views
2

我在尋求信息。 我和其他像我這樣的學生必須在Matlab中創建聲音。我們創建它們,我們還必須創建一個interactif接口來播放這些聲音。如何在matlab中使用KeyPressFCN並創建函數?

所以我們創建了一個鋼琴,當我們點擊一​​個按鍵,它的播放聲音(即功能)。

我們也希望我們能夠推動調用該函數的鍵盤的鍵。我們聽說過KeyPressFCN,但我們不知道如何使用它,因爲當我們搜索每個教程時,他們沒有提供足夠的信息。

所以,當我們右鍵點擊我們想要的元素時,我們稱之爲KeyPressFCN,下一步是什麼?我們必須做些什麼才能將該功能「放入」該KeyPressFCN。

例如,使聲音之一,我們有:

% --- Execution lors d'un appui sur le bouton Do (première blanche) 
function pushbutton1_Callback(hObject, eventdata, handles) 
octave = str2double(get(handles.zone1,'String')); 
frequence = 2093; %--- Fréquence initialement Do6 
frequence2 = frequence./ octave; 
son = sin(2*pi*frequence2*(0:0.000125:0.2)); 
sound(son); 

回答

12

其實我只是引用Matlab的文檔和幫助。

  1. 如果您使用的GUIDE右鍵點擊你的身材(沒有任何物體)>>查看回調>> KeyPressFcn,然後它會自動生成以下功能:各地

    function figure1_KeyPressFcn(hObject, eventdata, handles) 
    % hObject handle to figure1 (see GCBO) 
    % eventdata structure with the following fields (see FIGURE) 
    % Key: name of the key that was pressed, in lower case 
    % Character: character interpretation of the key(s) that was pressed 
    % Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed 
    % handles structure with handles and user data (see GUIDATA) 
    
    % add this part as an experiment and see what happens! 
    eventdata % Let's see the KeyPress event data 
    disp(eventdata.Key) % Let's display the key, for fun! 
    

    播放用你的鍵盤看到eventdata。顯然這個數字在你輸入時必須是活動的。

  2. 如果您使用的是uicontrol(而不是導遊)這是GUI進行

    (使用內聯函數)

    fig_h = figure; % Open the figure and put the figure handle in fig_h 
    set(fig_h,'KeyPressFcn',@(fig_obj,eventDat) disp(['You just pressed: ' eventDat.Key])); 
    % or again use the whole eventDat.Character or eventDat.Modifier if you want. 
    
  3. 或者,如果你不想使用內聯的編程方法功能:

    fig_h = figure; 
    set(fig_h,'KeyPressFcn', @key_pressed_fcn); 
    

    ,然後定義喜歡你key_pressed_fcn:(創建命名一個新的M文件:key_pressed_fcn.m,當然你可以使用任何ñ但是與上面的KeyPressFcn名稱相同)

    function key_pressed_fcn(fig_obj,eventDat) 
    
    get(fig_obj, 'CurrentKey') 
    get(fig_obj, 'CurrentCharacter') 
    get(fig_obj, 'CurrentModifier') 
    
    % or 
    
    disp(eventDat) 
    
  4. 或!使用腳本爲您KeyPressFcn回調函數

    fig_h = figure; 
    set(fig_h,'KeyPressFcn', 'key_pressed'); 
    

    ,然後寫KEY_PRESSED腳本:

    get(fig_h, 'CurrentKey') 
    get(fig_h, 'CurrentCharacter') 
    get(fig_h, 'CurrentModifier') 
    

MATLAB的幫助請參閱 「KeyPressFcn事件結構」: http://www.mathworks.com/help/matlab/ref/figure_props.html

+1

謝謝,這個答案解決了我的問題。 – omar

+1

非常好的帖子。 – Spacey

+0

考慮解決方案#2:如何獲得在主程序中按下的鍵?我的意思是,如果一個腳本創建了一個圖形,它如何對剛被按下的鍵作出反應?如何檢查'eventDat.Key'的值? – nightcod3r

相關問題