MATLAB: Make the Slider Move as the Music is Playing

guiMATLABmoving slidermusic

Hello,
I am having difficulty figuring out how to make the slider move in sync with the music from the signal playing from the axes of my GUI. I am new to Matlab and any hints would be great!
Thanks

Best Answer

If you are using the audioplayer to play the music, you can always assign a periodic timer to the player so that every one tenth of a second (or whatever your period is) you can update the slider position. For example, suppose we have a GUI with an axes, a push button, and a slider. The push button callback would start the audio and update the axes with the sample data, and could be written something like
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load handel;
handles.player = audioplayer(y, Fs);
% save all data to the handles object
handles.y = y';
handles.Fs = Fs;
handles.timeSec = length(y)/Fs;
handles.atSample = 0;
% assign a periodic timer to fire during playback
set(handles.player,'TimerFcn',{@timerCallback,handles.figure1}, 'TimerPeriod', 0.1);
% save the updated handles object
guidata(hObject,handles);
% reset the axes and set some properties
cla(handles.axes1);
hold(handles.axes1,'on');
xlim(handles.axes1,[1 length(y)]);
% play the music
play(handles.player);
We simply initialize the player, assign a timer function, save the updated handles object, and play the audio. The timer callback would look something like
function timerCallback(hObject, event, hFig)
% get the handles structure
handles = guidata(hFig);
% determine the current sample
currSample = get(hObject,'CurrentSample');
% get all of the sound data
data = handles.y(handles.atSample+1:currSample);
% plot the most recent set of data
plot(handles.axes1,handles.atSample+1:currSample,data);
% update the handles object
handles.atSample = currSample;
guidata(hFig,handles);
% update the slider
if currSample > 1
sliderVal = min(1.0,currSample/length(handles.y));
set(handles.slider1,'Value',sliderVal);
end
Given that our timer period is 0.1 seconds, then whenever the timer callback fires we update the axes with the sample data, and update the position of the slider. (We use a percentage of the "read" samples to determine its position.)
See the attached GUI which implements the above.