Problem playing audiofile from UI.

2 views (last 30 days)
Hi, I´m coding a simple button to reproduce an audio file on the UI. There seems to be a problem because it will analyze the audio but does not reproduce it. Eventhough if I run the same code on a empty matlab project without UI it will play. What is missing or what is the problem with the UI?
function pushbutton1_Callback(hObject, eventdata, handles)
[a, fs]=audioread('909.wav')
p=audioplayer(a,fs)
play(p)

Accepted Answer

Geoff Hayes
Geoff Hayes on 20 Apr 2020
Camilo - I suspect that the problem is that the audio player p is a local variable in your function. So as soon as the last line of code in the function is executed, the function is finished and is removed from the function call stack and so all variables declared within are "destroyed" including p...and so playback will end before it begins. Since you are using GUIDE, you can get around this by saving the player to the handles structure so that it persists outside of this function:
function pushbutton1_Callback(hObject, eventdata, handles)
[a, fs]=audioread('909.wav')
handles.p=audioplayer(a,fs)
guidata(hObject, handles); % <------ important! saves the updated structure
play(handles.p)
Now p is part of handles (and you must call guidata to save this updated structure). Try this out and see what happens!
Alternatively, you can use playblocking instead of play as playblocking does not return control until playback completes.

More Answers (1)

Temirkhan Amanzhanov
Temirkhan Amanzhanov on 1 Jun 2020
I have the same problem in App Designer. Could you help me please?

Community Treasure Hunt

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

Start Hunting!