Getting Wavread to import an audio file via a variable name

3 views (last 30 days)
Hi
I'm trying to get MATLAB to load a random audio file from a folder (i.e. to load a random 1 from the x audio files in the folder). I've created some code that creates a list of all the file names and randomly selects one, such that the filename of the .wav file is in a string variable (FileToPlay). However when I pass that string variable to my wavread function I get the following errors.
??? Error using ==> fileparts at 17 Input must be a row vector of characters.
Error in ==> wavread>open_wav at 193 [pat,nam,ext] = fileparts(file);
Error in ==> wavread at 65 [fid,msg] = open_wav(file);
Error in ==> get_random_file at 42 [File_Data,FS,NBITS,OPTS]=wavread(FileToPlay);
This is the relevant code. The CurrFold variable is just the name of the directory where the files are.
%Put metadata for folder in variable (not really sure what the index bit
%does)
FoldData = dir(CurrFold);
FoldIndex = [FoldData.isdir];
%Gets list of files in folder
FileList = {FoldData(~FoldIndex).name};
%Transpose resultant row vector into column vector
FileList = FileList';
%Get number of files
[FileCount] = size(FileList,1);
%create random number with upper limit of nbr of files (i.e. 1 - max number
%of files
n = ceil(FileCount*rand(1,1));
%Select file based on random number generated
FileToPlay = FileList(n);
%Remove any extra space
FileToPlay = strtrim(FileToPlay);
%Import file
[File_Data,FS,NBITS,OPTS]=wavread(FileToPlay);
If I replace FileToPlay in the wavread statement with the name of a wav file in quotations (i.e. 'noise.wav') then it works fine, so it's not that it can't find the location of the wav file, or some basic coding error. It must be that FileToPlay isn't holding the name of the file properly. Removing the strtrim function doesn't help either.
Thanks Rob

Accepted Answer

Jan
Jan on 18 May 2011
This replies a scalar cell string:
FileToPlay = FileList(n);
Use this to get the string:
FileToPlay = FileList{n}; % *curly* braces

More Answers (1)

Rob H
Rob H on 18 May 2011
Hi
That works thanks. What is the difference between (n) and {n} then, i.e. what is the difference between a 'scalar cell string' and a normal string?
I suspected it was something to do with the value held in FileToPlay but I couldn't identify what was wrong from it just by looking at it.
Thanks Rob
  1 Comment
Jan
Jan on 18 May 2011
CellString = {'1st', '2nd', '3rd', 'different lengths'};
CellString(1) is {'1st'} then: a list of strings with length 1. CellString(1:2) is {'1st', '2nd'). Cellstring{1} is the string '1st', which can be used for printing etc. See "docsearch('cell string')".

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!