在IOS上可以用MPMoviePlayerViewController实现在线播放音频,但是当网络不理想的情况下客户体验总不是太好,所以采用了,先下载下来,然后播放。
1.下载音频
NSString *soundhttpURL = [[NSString alloc] initWithFormat:@"http://114.112.55.2:6080/audio/question/audio_"];
NSString *qid = [currentQuestion objectForKey:@"qid"];
NSString *soundURLStr = [NSString stringWithFormat:@"%@%@%@",soundhttpURL,qid,@".wav"];
NSURL *soundURL = [NSURL URLWithString:soundURLStr];
NSLog(@"soundURL:%@",soundURL);
NSDate *date = [NSDate date];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:soundURL];
NSURLResponse *response;
NSError *error;
NSData* result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSLog(@"Response expects %lld bytes", [response expectedContentLength]);
NSLog(@"Response suggested file name: %@", [response suggestedFilename]);
if ([response suggestedFilename])
self.savePath = [DEST_PATH stringByAppendingString:[response suggestedFilename]];
if (!result)
NSLog(@"Error downloading data: %@.", [error localizedDescription]);
else if ([response expectedContentLength] < 0)
NSLog(@"Error with download. Carrier redirect?");
else
{
NSLog(@"Download succeeded.");
NSLog(@"Read %d bytes", result.length);
NSLog(@"Elapsed time: %0.2f seconds.", -1*[date timeIntervalSinceNow]);
[result writeToFile:self.savePath atomically:YES];
NSLog(@"Data written to file: %@.", self.savePath);
}
[self performSelectorOnMainThread:@selector(playQuestionSound:) withObject:soundURL waitUntilDone:NO];//播放问题音频
2.播放音频
- (void) playQuestionSound:(NSURL *)soundURL {
//播放问题音频
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
NSURL *fileURL = [NSURL fileURLWithPath:self.savePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
[fileURL release];
[player setVolume:15.0];
[player play];
}