设计一个matlab GUI界面,要求可以选择音调,播放钢琴曲
时间: 2024-05-09 13:14:16 浏览: 12
以下是一个简单的 MATLAB GUI 界面,可以让用户选择音调并播放钢琴曲。这个界面使用了 MATLAB 自带的音频播放函数 `sound()`。
```matlab
function piano_GUI()
% Create a simple piano GUI that plays notes when clicked
% Set up the figure
fig = figure('Position', [100 100 500 300], 'MenuBar', 'none', ...
'ToolBar', 'none', 'NumberTitle', 'off', 'Name', 'Piano');
% Create an axes to hold the piano keys
ax = axes('Position', [0.05 0.3 0.9 0.6], 'XTick', [], 'YTick', []);
% Create the piano keys
nkeys = 13;
for i = 1:nkeys
% Determine the key color
if mod(i, 2) == 0
color = 'black';
else
color = 'white';
end
% Create the key rectangle
pos = [i-1, 0, 1, 1];
rectangle('Position', pos, 'FaceColor', color, 'EdgeColor', 'none');
% Add a callback to play the note when the key is clicked
set(ax, 'ButtonDownFcn', {@play_note, i-1});
end
% Create a popup menu to select the note
notes = {'A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab'};
note_popup = uicontrol('Style', 'popupmenu', 'String', notes, ...
'Position', [50 50 100 30]);
% Create a pushbutton to play the selected note
play_button = uicontrol('Style', 'pushbutton', 'String', 'Play', ...
'Position', [200 50 100 30], 'Callback', {@play_selected_note, note_popup});
% Create a pushbutton to close the GUI
close_button = uicontrol('Style', 'pushbutton', 'String', 'Close', ...
'Position', [350 50 100 30], 'Callback', 'close(gcf)');
% Define the note frequencies
frequencies = [220 233.08 246.94 261.63 277.18 293.66 311.13 329.63 349.23 369.99 392.00 415.30];
% Callback function to play a note when a key is clicked
function play_note(~, ~, key)
% Determine the note frequency
note_idx = mod(key, 12) + 1;
freq = frequencies(note_idx);
if key >= 12
freq = freq * 2;
end
% Play the note
duration = 0.5;
t = 0:1/44100:duration;
y = sin(2*pi*freq*t);
sound(y, 44100);
end
% Callback function to play the selected note
function play_selected_note(~, ~, note_popup)
% Determine the selected note frequency
note_idx = get(note_popup, 'Value');
freq = frequencies(note_idx);
% Play the note
duration = 0.5;
t = 0:1/44100:duration;
y = sin(2*pi*freq*t);
sound(y, 44100);
end
end
```
这个界面包括一个简单的钢琴键盘,用户可以点击键盘上的键来播放相应的音符。同时,界面还包括一个下拉菜单和一个按钮,用于选择要播放的音符。