matlabmatlab-guideplayback

Matlab: How to call play(recorder) from GUI


If entered at the command line in Matlab 2016, the following lines will create an audiorecorder object, start it recording, stop it recording, write the recorded samples to a wav, and play the samples from the recorder object (i.e., not from the newly written wav file):

rec = audiorecorder(44100, 16, 1);
record(rec);  % User speaks now
stop(rec);
audiowrite('foo.wav', getaudiodata(rec), 44100);
play(rec);

I am trying to partition this into a three button GUI (created with GUIDE) with the following functionality:

  1. Start button, which starts a created recorder
  2. Stop button, which stops the recorder AND saves the wav file
  3. Playback button, which plays back the samples from the recorder

(The idea is to be able to record small samples of text, quickly listen for a first pass of quality, and decide whether or not to record over or to advance to the next sample.

Create the recorder object (among other things) in the initial setup for the GUI:

function ReadingScript_OpeningFcn(hObject, eventdata, handles, varargin)
   recorder = audiorecorder(Fs, nbits, nChannels);

Start the recorder object:

function startRecord_Callback(hObject, eventdata, handles)
   global recorder
   set(handles.status,'String', 'Recording');
   record(recorder);

Stop the recorder object AND save samples to a file:

function stopRecord_Callback(hObject, eventdata, handles)
   global recorder
   global wavname    
   stop(recorder);
   audiowrite(wavname, getaudiodata(recorder), 44100)

Play the samples back:

function PlayBack_Callback(hObject, eventdata, handles)

   global recorder 
   play(recorder)

Everything here works except playing the samples back. Samples are recorded into the recorder, which starts and stops with the correct button presses, and a wav file is saved. But the samples will not play. I even know the playback button is firing because of the intentional missing semicolon, which causes the details of the recorder object to be printed to screen, which also verifies that samples are still in it.

What exactly am I missing, that will make the audio play?


Solution

  • There seems to be a quirk of the audiorecorder that means it won't play within a GUI.

    In order to get it working I needed to use playblocking with an audioplayer object as shown below

    global recorder
    disp('playing');
    player = audioplayer(getaudiodata(recorder),44100,16);
    playblocking(player);