Array of CFURLRefs in a struct

Discussion in 'iOS Programming' started by neil.b, Dec 12, 2008.

  1. macrumors member

    neil.b

    Joined:
    Nov 20, 2008
    #1
    I'm trying to define a struct to create a simple sound object that contains a list of sound files and some flags;

    Code:
    #define NUMBER_OF_SOUNDS_IN_SET 3
    
    typdef struct {
            CFURL soundURL[NUMBER_OF_SOUNDS_IN_SET];
            BOOL playing;
            BOOL monophonic;
    } SimpleSoundStructure;
    
    SimpleSoundStructure mySimpleSound;
    
    -(void) initSimpleSoundStructure
    {
            NSArray *sampleFileNames = [NSArray arrayWithObjects:
            @"sample1.aif",
            @"sample2.aif",
            @"sample3.aif",
            nil];
    
            NSString *aSampleFile;
            for (int i = 0; i < NUMBER_OF_SOUNDS_IN_SET; i++)
            {
               mySimpleSound.soundURL[i] = (CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:aSampleFile ofType:NULL]];
            }
    }
    
    -(void) playASound:(int)sound
    {
            AudioServicesCreateSystemSoundID (mySimpleSound.soundURL[sound], &mySoundSet.soundObject[sound]);
    	AudioServicesPlaySystemSound(mySoundSet.soundObject[sound]);
    }
    
    But I always get a "BAD ACCESS" error (and program termination) when I try to call the AudioServiceCreateSystemSoundID function in the playASound function.

    What is weird is that if I NSLog mySimpleSound.soundURL in the for...loop in the init function, it has the correct path to the sample files. But if I do the same in the playASound function, the log shows the path to be something like "UI...white space" (sorry, I've changed the function so can't remember the exact error).

    What's even weirder, if I put a AudioServiceCreateSystemSoundID call in the init for...loop, when I retrieve the path in the playASound function the path to the sample is now correct and the function works.

    Pulling my hair out on this one :(
     
  2. macrumors newbie

    Joined:
    Aug 30, 2007
    #2
    My first guess is that you need to retain the NSURL returned from [NSURL fileURLWithPath:]. There's a very good chance the NSURL is being autoreleased somewhere between your init method and your playASound method.

    This also means that you need to remember to release these NSURLs at some point as well.
     
  3. thread starter macrumors member

    neil.b

    Joined:
    Nov 20, 2008
    #3
    Spot on, thank you very much! :D

    Now to come up with a smart way of releasing the NSURLs.... :)
     

Share This Page