My app downloads an mp3 from our server and plays it back to the user. The file is 64 kbps (which is well within the acceptable range for iPhone if I understand correctly).
We were dealing with the same issue - we had to write the file to disk first. What I found eventually was that the data we were downloading had extra, blank bytes at the beginning. When reading from disk using initWithContentsOfURL
, AVAudioPlayer knew how to deal with this, but when loading from NSData using initWithData
, it did not. Trimming those bytes fixed it.
If your product name contains space, you will receive the error.
My project's product name was: Panorama 1453 TR. initWithContentsOfURL
method cannot fetch file path. so it was not working.
you can put a breakPoint to NSURL *fileURL =
. After a step you can see fileURL what data has.
I changed to Panorama1453TR , it did work.
From iOS 7 AVAudioPlayer has new initializer
NSError *error;
[[AVAudioPlayer alloc] initWithData:soundData fileTypeHint:AVFileTypeMPEGLayer3 error:&error]
The supported UTIs
NSString *const AVFileType3GPP;
NSString *const AVFileType3GPP2;
NSString *const AVFileTypeAIFC;
NSString *const AVFileTypeAIFF;
NSString *const AVFileTypeAMR;
NSString *const AVFileTypeAC3;
NSString *const AVFileTypeMPEGLayer3;
NSString *const AVFileTypeSunAU;
NSString *const AVFileTypeCoreAudioFormat;
NSString *const AVFileTypeAppleM4V;
NSString *const AVFileTypeMPEG4;
NSString *const AVFileTypeAppleM4A;
NSString *const AVFileTypeQuickTimeMovie;
NSString *const AVFileTypeWAVE;
At long last i have found a solution to this problem! Instead of initializing the audio player with the NSData object, I saved the file to the Documents folder, and then initialized the player with the file URL
//download file and play from disk
NSData *audioData = [NSData dataWithContentsOfURL:someURL];
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@.mp3", docDirPath , fileName];
[audioData writeToFile:filePath atomically:YES];
NSError *error;
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if (player == nil) {
NSLog(@"AudioPlayer did not load properly: %@", [error description]);
} else {
[player play];
}
When the app is done with the file, it can be deleted. Hope that his helps more than just me!