File: ef230-2023-08/www/examples/sound_fader.m Download
%! Demonstrate playing a music file with a fade in and out
% University of Tennessee : EF 230 Fall, 2009 : Will Schleter

function sound_fader
clear all; close all; clc;

% get the file from the web site, if necessary
% matlab has functions to read au and wav files
% you'll need to convert to one of these formats
% or search for and install a toolbox to read/write mp3 files
if ~exist(fname,'file')
  h=msgbox('Loading file from web site, please wait...');
  urlwrite([url fname],fname);

size=auread(fname,'size'); % file size
[y,fs,bits]=auread(fname,1); % read 1 sample just to get the sample rate
[y,fs,bits]=auread(fname,fs*10); % read the first 10 seconds
y=fade(y,fs,0,2,0,1); % fade in first 2 seconds
y=fade(y,fs,7,10,1,0); % fade out last 3 seconds
ap=audioplayer(y,fs); % init the player
play(ap); % play the tweaked data
waitfor(msgbox('Music should be playing in background'));
% Note - allowing this function to end clears the ap object and stops the
% music. If you want music to play during other functions assign it to a
% global variable or use assignin('base','ap',ap);

function r=fade(data,fs,t1,t2,lev1,lev2)
% this function takes sound data and applied a fade to it
% data: the sound data
% fs: sampling rate
% t1: start time for fade (seconds)
% t2: end time for fade (seconds)
% lev1: starting level (0 to 1, 1 is 100%)
% lev2: ending level (0 to 1, 1 is 100%)
i1=t1*fs+1; % first index
i2=t2*fs+1; % last index
range=i2-i1; %
r=data; % init the results
% modify the levels
for i=0:range-1
    p=lev1+(lev2-lev1)*(10.^(i/range-1)); % log fade
    % p=lev1+(lev2-lev1)*(i/range); % linear fade