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 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)
Read and Write Audio Files Frame-by-Frame
To read audio frame-by-frame into the workspace and then write audio frame-by-frame to your speakers, use the dsp.AudioFileReader
and audioDeviceWriter
functions.
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")
fileReader = dsp.AudioFileReader with properties: Filename: '/mathworks/devel/bat/filer/batfs2566-0/Bdoc24b.2725827/build/runnable/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
Create an 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.
release(fileReader) release(deviceWriter)
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
audioDeviceReader
| audioDeviceWriter
| audioPlayerRecorder
| dsp.AudioFileWriter
| dsp.AudioFileReader
| asiosettings
| getAudioDevices