2015-11-03 88 views
0

我正在使用AFNetworking從服務器上下載音頻文件。該文件正在成功下載,因爲我可以通過進度模塊查看它。 我將它存儲在文檔目錄中,但後來無法播放它。 這裏是我的代碼: -下載音頻,無法使用AVAudioPlayer播放

-(void)downloadAudioFileFromUrl:(NSString *)str_url{ 

    [SVProgressHUD show]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:str_url]]; 
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"momentsAudioToast.mp3"]; 
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO]; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
     NSLog(@"Successfully downloaded file to %@", path); 
     [SVProgressHUD dismiss]; 

     if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { 


      [self playSound:path]; 
     } 



    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"Error: %@", error); 
     [SVProgressHUD dismiss]; 
    }]; 

    [operation setDownloadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { 

     //[progressView setProgress: totalBytesWritten*1.0f/totalBytesExpectedToWrite animated: YES]; 
     NSLog(@"downloaded %lld of %lld bytes and progress is %f", totalBytesWritten, totalBytesExpectedToWrite, totalBytesWritten*1.0f/totalBytesExpectedToWrite); 
     if(totalBytesWritten >= totalBytesExpectedToWrite) 
     { 
      //progressView.hidden = YES; 
     } 
    }]; 


    [operation start]; 


} 

- (void)playSound:(NSString *)path { 
    [self.player prepareToPlay]; 
    //UIButton *audioButton = (UIButton *)sender; 
    //[audioButton setImage:[UIImage imageNamed:@"sound_preview.png"] forState:UIControlStateNormal]; 
    NSData *audioData = [NSData dataWithContentsOfFile:path options: 0 error:nil]; 

    self.player = [[AVAudioPlayer alloc] initWithData:audioData error:nil]; 
    double duration = [self.player duration]; 

    NSLog(@"%f", duration); 
    NSError * error; 

    self.player.delegate = self; 
    self.player.numberOfLoops = 0; 
    if (error) { 
     NSLog(@"Error: %@",[error description]); 
    } 
    else { 
     self.player.delegate = self; 
     [self.player play]; 
    } 
} 

請幫助,如果我做錯了什麼。

在此先感謝。

回答

0

首先,確保你保持強引用AVAudioPlayer實例player這樣的:

@property (nonatomic, strong) AVAudioPlayer *player; 

其次,最有可能的,這將是路徑相關的問題。嘗試在播放時重建路徑。

第三,,仔細檢查文件是否存在,並在任何音頻播放器中播放時播放。

+0

我已經在第二方法中,如果([[的NSFileManager defaultManager] fileExistsAtPath:路徑])加入該條件和它返回真,仍持續時間來0.000。另外強烈的參考已經完成。請提出建議。 –

0

在你的情況下,如果你聲明音頻播放器完美。

如果從Web服務的音頻文件中獲取NSData,還可以設置代表&。

然後您需要再插入一行代碼並再次檢查。

[self.player setVolume: 1.0]; 
相關問題