AVAudioPlayer with external URL to *.m4p

2019-01-11 18:31发布

问题:

My Problem is the following. I got this code and i guess a corrupt NSURL since the AVAudioPlayer is nil after initializing:

NSString *dummyURLString = @"http://a825.phobos.apple.com/us/r2000/005/Music/d8/a8/d2/mzi.jelhjoev.aac.p.m4p";
NSError *error;
NSURL *url = [NSURL URLWithString:dummyURLString]; 
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[player play];

Any suggestions what is going wrong here?

The &error shows this:

Error Domain=NSOSStatusErrorDomain Code=-43 "Operation could not be completed. (OSStatus error -43.)"

回答1:

I tried this first but got error 2003334207:

NSData *soundData = [NSData dataWithContentsOfURL:URL];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:soundData error:&error];

Seems that AVAudioPlayer really wants a file. So I put the data into a file first:

NSURL *url = [NSURL URLWithString:@"http://a825.phobos.apple.com/us/r2000/005/Music/d8/a8/d2/mzi.jelhjoev.aac.p.m4p"]; 
NSData *soundData = [NSData dataWithContentsOfURL:url];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                        NSUserDomainMask, YES) objectAtIndex:0] 
                        stringByAppendingPathComponent:@"sound.caf"];
[soundData writeToFile:filePath atomically:YES];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL
                fileURLWithPath:filePath] error:NULL];  
NSLog(@"error %@", error);


回答2:

AVAudioPlayer only works with local URL's. It must be a File URL (file://)

See Apple's Technical Q&A QA1634



回答3:

Instead of using the AVAudioPlayer you can use the AVPlayer. The AVPlayer works as well with remote URLs