How do I design my code so that when the user presses a button, a sound plays?

5 ビュー (過去 30 日間)
Kyra
Kyra 2022 年 12 月 18 日
コメント済み: Kyra 2022 年 12 月 19 日
I have coded 5 songs and a function that will play those songs. I have also designed an app layout to display a play button for each of these songs. My issue now is that I'm unsure how to code the buttons in order to play the songs. I've done a lot of research and can't find anything that works for this project. I've attached my code here:
function kburnside_project()
fs = 44100;
uiwait(msgbox('Hello welcome to the music selection program where you can listen to a Christmas song of your choice!'))
stop1 = rest(4,fs);
stop2 = rest(8,fs);
stop3 = rest(16,fs);
a_4 = key(52,4,fs);
b_4 = key(54,4,fs);
c_4 = key(56,4,fs);
d_4 = key(57,4,fs);
e_4 = key(59,4,fs);
f_4 = key(61,4,fs);
g_4 = key(63,4,fs);
a_8 = key(52,8,fs);
b_8 = key(54,8,fs);
c_8 = key(56,8,fs);
d_8 = key(57,8,fs);
e_8 = key(59,8,fs);
f_8 = key(61,8,fs);
g_8 = key(63,8,fs);
a_16 = key(52,16,fs);
b_16 = key(54,16,fs);
c_16 = key(56,16,fs);
d_16 = key(57,16,fs);
e_16 = key(59,16,fs);
f_16 = key(61,16,fs);
g_16 = key(63,16,fs);
song1 = [e_8 e_8 e_4 e_8 e_8 e_4 e_8 g_8 c_8 d_8 e_4];
sound(song1,fs,24);
song2 = [g_16 a_8 g_16 e_8 c_8 a_8 g_4 g_16 a_16 g_16 a_16 g_8 c_8 b_4 f_16 g_8 f_16 d_8 b_8 a_8 g_4 g_16 a_16 g_16 a_16 g_8 a_8 e_4];
sound(song2,fs,24)
song3 = [c_16 c_16 c_8 b_16 b_16 b_8 a_16 b_16 a_16 e_4 a_16 b_16 a_16 e_4 g_8 a_16 b_16 a_16 f_4 d_16 e_8 f_16 g_16 a_8 g_16 d_16 e_16 f_16 g_4 a_16 b_16 a_16 b_16 a_8 a_8 e_16 e_4];
sound(song3,fs,24)
song4 = [c_8 b_16 a_8 g_8 f_8 g_8 a_8 f_8 g_16 a_16 b_16 g_16 a_4 g_16 f_8 e_8 f_8];
sound(song4,fs,24)
song5 = [c_4 b_8 a_8 g_8 f_8 e_4 d_4 c_4 g_8 a_4 a_8 b_4 b_8 c_4];
sound(song5,fs,24)
function wave = key(p, n, fs)
t = 0:1/fs:4/n;
idx = 440*2^((p-49)/12);
mid = (t(1)+t(end))/2;
tri = -(abs(t-mid)-mid);
tri = tri./max(tri);
wave = (sin(2*pi*idx*t)).*tri;
function wave = rest(n,fs)
t = 0:1/fs:4/n;
tt = 4/n:-1/fs:0;
wave = 0*sin(2*pi*t).*exp(tt);

回答 (1 件)

cr
cr 2022 年 12 月 18 日
In the app you will see callback functions for each button. Eg you right click a button and select add buttonpressed callback and appdesigner (or guide) will create a placeholder function for you to put the code in. Inside the callback just put the code that plays the sound. Also for playing sounds audioplayer() is simpler to use.
  3 件のコメント
cr
cr 2022 年 12 月 19 日
Is your song playing when the equivalent code is put in a script without functions?
Kyra
Kyra 2022 年 12 月 19 日
Yes

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeAudio and Video Data についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by