Generation of Audio Using the Sound Card

This example shows how to output data to a sound card using the data acquisition analog output object. The data from HANDEL.MAT will be used in this example. As the data is being output, the data will be displayed in the axes window.

Note: This can only be run using the 32-bit version of MATLAB® and Data Acquisition Toolbox™. To learn more about using data acquisition devices on other platforms, see this example

First, find any running data acquisition objects and stop them. This stops all running data acquisition objects from interfering with this example. This code is usually not necessary outside this example unless there are multiple data acquisition objects running.

if (~isempty(daqfind))

To begin, an analog output object associated with the winsound device is created. Two channels are then added to the analog output object, ao. This will allow the winsound device to run in stereo mode.

ao = analogoutput('winsound', 0);
addchannel(ao, [1 2]);

HANDEL.MAT contains two variables:

   y  - the data that will be output to the sound card
   Fs - the sample rate at which the data was originally sampled.

The data and sample rate are loaded from HANDEL.MAT into the MATLAB® workspace.

load handel

The analog output object is configured to use the loaded sample rate. For soundcards, we'll turn off the StandardSampleRate property, in order to allow optimal playback.

ao.StandardSampleRates = 'Off';
ao.SampleRate = Fs;
Fs =


For the loaded data to be output, it must first be queued in the data acquisition engine with the PUTDATA command. The data being queued in the data acquisition engine must consist of a column of data for each channel of the analog output object.

data = [y y];
putdata(ao, data);

The analog output object and the data acquisition engine are started with the START command. Starting the output object means that the hardware device and the data acquisition engine are both running. Running does not necessarily mean that the data is being output. For data to be output, a trigger must occur. By default, an immediate trigger occurs as soon as the object is started.

A plot is drawn while the sound plays for added effects.

startindex = 1;
increment = 500;

while isrunning(ao)  % do the plot
    while (ao.SamplesOutput < startindex + increment -1), end
        x = ao.SamplesOutput;
		ylim([-0.8 0.8])
		xlim([1 increment])
        startindex =  startindex+increment;

When the data has been output, the analog output object is stopped automatically. The analog output object should be deleted with the DELETE command to free memory and other physical resources.

Was this topic helpful?