Main Content

Audio Input and Audio Output

This example shows how to read audio from a file and write audio to your speakers.

To read an entire audio file into the workspace and then write the entire audio signal to your speakers, you can use the audioread and soundsc functions. Call audioread with a file name to read the entire audio file and the sample rate of the audio. Call soundsc with the audio data and sample rate to play the audio to your default speakers.

[audioData,fs] = audioread("SpeechDFT-16-8-mono-5secs.wav");
soundsc(audioData,fs)

The audiostreamer object provides a more flexible I/O interface for playing and recording audio. You can play the same entire audio signal by calling play with the audiostreamer.

as = audiostreamer("player",fs);
play(as,audioData)

The audiostreamer object also supports playing audio frame-by-frame, which is useful for streaming workflows.

Create a dsp.AudioFileReader object to read audio from a file frame-by-frame. The audio file reader saves the sample rate of the audio file to the SampleRate property.

fileReader = dsp.AudioFileReader("Filename","SpeechDFT-16-8-mono-5secs.wav");

Use the same audiostreamer object you already created and explicitly set the SampleRate property to make sure it is the same as the sample rate of the file reader.

as.SampleRate = fileReader.SampleRate;

In a loop, read from the file and write to the device. While the loop runs, audio is played to your default audio device.

while ~isDone(fileReader)
    
    % Read one frame of audio data from the file.
    audioData = fileReader();
    
    % Write one frame of audio data to your speakers.
    play(as,audioData);
    
end

As a best practice, release the file and audio device when you are done.

release(fileReader)
release(as)

To learn how to implement other audio I/O configurations, such as reading from a microphone or writing to a speaker, see Real-Time Audio in MATLAB.

See Also

| | | |

Topics