Domanda

Hi I'm using the following code to play an audio file

NSString *stringPath = [[NSBundle mainBundle]pathForResource:@"audioFileName" ofType:@"mp3" inDirectory:@"/Downloads"];
    NSURL *url = [NSURL fileURLWithPath:stringPath];
    NSError *error;

    avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
    avPlayer.delegate = self;
    [avPlayer play];

But I get an error because my audio files I located in a folder called "Downloads" Path: AppName/Library/ApplicationSupport/Downloads/audioFileName.mp3

The error I get is that the string stringPath is nil probably because that line of code is written wrong. I know for sure the file is there!

Heres an image using file browsing software

enter image description here

So my question how do i modify the above code to point to my downloads directory when playing a audio file. Thanks

Ive even tried putting the whole path like this.

NSString *stringPath = [[NSBundle mainBundle]pathForResource:@"audioFileName" ofType:@"mp3" inDirectory:@"Library/Application Support/Downloads"];

Status update!

I now do the following and the error is gone but not sure if its pointing to the correct folder still and if so is it possible I don't have permissions to use the files within it. This is a directory i created so is changing permissions to it after its created something I had too do?

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

NSString *libraryDirectory = [paths objectAtIndex:0];

NSString *stringPath = [[libraryDirectory stringByAppendingPathComponent:@"Downloads"] stringByAppendingPathComponent:@"audioFileName.mp3"];
È stato utile?

Soluzione

I believe pathForResource is only for files you include with your app. You have made the audio file in the Library folder which is not in your .app folder... so you could try to use something like:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

NSString *libraryDirectory = [paths objectAtIndex:0];

NSString *stringPath = [[libraryDirectory stringByAppendingPathComponent:@"Downloads"] stringByAppendingPathComponent:@"audioFileName.mp3"];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top