1

好吧,我已经阅读了很多与我类似的问题,但我仍然无法解决问题。

我打算从 Internet 下载音频文件,然后播放它们。使用 NSURLConnection,我成功地下载了文件。这是我下载文件的代码。

- (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!");
}

然后为了保存和播放文件,我写了以下内容

- (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!");
}
}

这是我在运行后从控制台得到的

2013-08-23 13:57:51.636 Download_2[4461:c07] didfinishloading 收到 34512 字节的数据 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 下载_2[4461:c07] 播放!

似乎一切正常,但问题是我在运行项目时听不到任何声音!

4

3 回答 3

3

播放远程文件有更简单的方法 - 使用AVPlayer而不是AVAudioPlayer. 它也更加用户友好,因为 AVPlayer 可以在下载过程中播放文件。

- (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");
        }
    }
}

您还可以在此处找到示例项目

于 2013-08-21T13:07:29.527 回答
2

你可以试试这个

-(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];
}
}
于 2013-08-21T12:51:14.010 回答
2

问题是我从未创建过目录“myFolder”,NSDocumentationDirectory 也应该更改为 NSDocumentDirectory 才能写入。这是更正后的代码

- (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");
}

}
于 2013-08-27T08:05:26.133 回答