c4

Loading an audio sample from the documents folder


I'm trying to have an app play audio files added via itunes file-sharing. I've managed the app to retrieve the app's sandbox folder's content, but I'm not able to load such files into a C4Sample by specifying the complete path.

NSString *documentsFolder;
NSString *clickAudioPath;
C4Sample *clicksample;
-(void)setup {
    // Retrieve the app's Documents folder
    documentsFolder = [self applicationDocumentsDirectory];
    clickAudioPath = [NSString stringWithFormat:@"%@/click.mp3", documentsFolder];    

    // Add test click audio
    clicksample = [C4Sample sampleNamed:clickAudioPath];
    [clicksample prepareToPlay];
    [clicksample play];
}
// Get Documents folder
- (NSString *) applicationDocumentsDirectory{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

The above code doesn't play any sound, although I've doubled checked that clicksample actually refers to an existing file. How can I specify a complete path instead of just a name to load the audio?


Solution

  • Add a new method as below.

    -(id) initWithURL:(NSURL *) soundFileURL
    {
        self = [super init];
        if(self != nil) {
            _player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
            self.enableRate = YES;
            self.player.delegate = self;
            [self setup];
       }
       return self;
    }