Audio Input and Audio Output
This example shows how to read audio from a file and write audio to your speakers.
Read and Write Entire Audio Files
To read an entire audio file into the workspace and then write the entire audio signal to your speakers, use the
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)
Read and Write Audio Files Frame-by-Frame
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
fileReader = dsp.AudioFileReader("Filename","SpeechDFT-16-8-mono-5secs.wav")
fileReader = dsp.AudioFileReader with properties: Filename: '/mathworks/devel/bat/Bdoc23b/build/matlab/toolbox/audio/samples/SpeechDFT-16-8-mono-5secs.wav' PlayCount: 1 ReadRange: [1 Inf] SamplesPerFrame: 1024 OutputDataType: 'double' Use get to show all properties
audioDeviceWriter object to write audio to your speakers. Set the sample rate of the
audioDeviceWriter object to the sample rate of the audio file.
deviceWriter = audioDeviceWriter("SampleRate",fileReader.SampleRate)
deviceWriter = audioDeviceWriter with properties: Device: 'Default' SampleRate: 8000 Use get to show all properties
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. deviceWriter(audioData); end
As a best practice, release the file and audio device when you are done.
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.