Well I've read so many similar questions to mine, but I still can not solve the problem.
I'm going to download audio files from Internet and then play them. Using NSURLConnection, I managed to download the file successfully. Here is the code I to download the file.
- (IBAction)download:(id)sender
{
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.dailywav.com/0813/bicycles.wav"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
receivedData = [NSMutableData data] ;
} else {NSLog(@"no connection!");
}
Then for saving and playing the file I wrote the following
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(@"didfinishloading Received %d bytes of data",[receivedData length]);
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSLog(@"%@", [documentPaths objectAtIndex:0]);
NSString *documentDirectoryPath = [documentPaths objectAtIndex:0];
NSString *folderPath = [documentDirectoryPath stringByAppendingPathComponent:@"myFolder/doScience.wav"];
[receivedData writeToFile:folderPath atomically:YES];
NSError *error;
AVPlayer * player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:folderPath]];
if (player == nil) {
NSLog(@"AudioPlayer did not load properly: %@", [error description]);
} else {
[player play];
NSLog(@"playing!");
}
}
And here is what I get from console after running
2013-08-23 13:57:51.636 Download_2[4461:c07] didfinishloading Received 34512 bytes of data 2013-08-23 13:57:51.637 Download_2[4461:c07] /Users/my_name/Library/Application Support/iPhone Simulator/6.1/Applications/88561BAC-66BF-4774-A626-0CEFEC82D63E/Library/Documentation 2013-08-23 13:57:51.639 Download_2[4461:c07] playing!
Seems everything is working, but the problem is I can't hear anything when I run the project!
There is easier way to play remote files - use AVPlayer
instead of AVAudioPlayer
. It's also more user-friendly since AVPlayer can play files during download process.
- (IBAction)playSound:(UIButton *)sender
{
NSURL *url = [[NSURL alloc] initWithString:@"http://www.dailywav.com/0813/bicycles.wav"];
AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];
player = [AVPlayer playerWithPlayerItem:anItem];
[player addObserver:self forKeyPath:@"status" options:0 context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (object == player && [keyPath isEqualToString:@"status"]) {
if ([player status] == AVPlayerStatusFailed) {
NSLog(@"AVPlayer Failed");
} else if ([player status] == AVPlayerStatusReadyToPlay) {
NSLog(@"AVPlayer Ready to Play");
[player play];
} else if ([player status] == AVPlayerItemStatusUnknown) {
NSLog(@"AVPlayer Unknown");
}
}
}
You can also find sample project here
You can try this ,
-(IBAction)download:(id)sender
{
NSData *audioData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.dailywav.com/0813/bicycles.wav"]];
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/bicycles.wav", docDirPath ];
[audioData writeToFile:filePath atomically:YES];
NSError *error;
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if (player == nil) {
NSLog(@"AudioPlayer did not load properly: %@", [error description]);
} else {
[player play];
}
}
The problem was that I've never made directory "myFolder", also NSDocumentationDirectory should be changed to NSDocumentDirectory to be able to write to. Here is the corrected code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(@"Succeed! Received %d bytes of data",[receivedData length]);
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSLog(@"%@", [documentPaths objectAtIndex:0]);
NSString *documentDirectoryPath = [documentPaths objectAtIndex:0];
NSString *folderPath = [documentDirectoryPath stringByAppendingPathComponent:@"myFile.wav"];
[receivedData writeToFile:folderPath atomically:YES];
NSURL *soundURL = [NSURL fileURLWithPath:folderPath];
NSError *error;
if ([[NSFileManager defaultManager] fileExistsAtPath:folderPath]) {
player = [[AVAudioPlayer alloc]initWithContentsOfURL:soundURL error:&error];
player.volume=0.5;
NSError *error = nil;
if (!error) {
[player play];
NSLog(@"File is playing!");
}
else{
NSLog(@"Error in creating audio player:%@",[error description]);
}
}
else{
NSLog(@"File doesn't exist");
}
}
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.