Here is my code, In this first I am calling mp3 url for downloading the audio data. then I am saving that data in local directory, After that I am playing audio from local file path but its not working AVAudioPlayer
throwing error. I have tried some other ways also but no one work for me. On simulator same code is working fine. And the audio url is playing like a charm in browser.
NSURL *urlll=[NSURL URLWithString:@"www.xyz.audio.mp3"];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:urlll] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *responce,NSData* data,NSError * error) {
if (error == nil)
{
indicator.hidden=YES;
[indicator stopAnimating];
if (data)
{
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@.mp3", docDirPath , @"Audio"];
[data writeToFile:filePath atomically:YES];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
AudioPlayer.delegate=self;
[AudioPlayer prepareToPlay];
if (AudioPlayer == nil) {
NSLog(@"AudioPlayer did not load properly: %@", [error description]);
} else {
[AudioPlayer play];
}
}
}
}];
But I am getting these kind of errors : E rror Domain=NSOSStatusErrorDomain Code=1685348671 "The operation couldn't be completed. (OSStatus error 1685348671.)
Please Help me :( .
In your code you save the audio to NSString *filePath
but you initiate with fileURL
. Could it be that you actually wanted to do this:
AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:&error];
If not then you should know that the error is reporting to you a kAudioFileInvalidFileError
. Which means the file is malformed. You could try other formats like . caf
or . aifc
or aiff
.
--edit--
Make sure the AVAudioPlayer
is a property in .m or .h file, so the memory allocation lasts after leaving the method:
@property (nonatomic,strong) AVAudioPlayer *AudioPlayer;
(side note: properties should start with lowercase -> audioPlayer
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.