2012-01-17 33 views
0

我已經搜索了很多試圖弄清楚這一點 - 我的代碼似乎確定,但功能並沒有反映出這一點。AVAudioPlayer不會播放現有文件第二次

我有一個呈現的視圖(它是一個錄音機視圖)。您可以按記錄,並將其記錄到文件中(數據存在於文件中)。然後,我可以通過播放按鈕播放文件(AVAudioPlayer指向該文件)。

但是當我關閉/駁回這一觀點,回來了 - 當遊戲被竊聽即使作爲文件的位置並沒有改變它應該是完全一樣的代碼的文件將無法播放。

更新:

似乎[audioPlayer播放]返回no。我也研究過這些數據。看來,當視圖再次出現,並加載這些數據它不正確加載(NSData的中的NSLog顯示主要的0) - 即使該文件存在,並且在它的數據(我可以看到並轉移到我的Mac後聽到)。

這使我懷疑,要麼我加載數據錯誤或avaudioplayer不會讀出於某種原因,數據...

請看看下面的代碼:

(NSString *) removeCharsFrom: (NSString *) remover { 

    remover = [remover stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
    remover = [remover stringByReplacingOccurrencesOfString:@" " withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"/" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"\\" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@":" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@";" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"(" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@")" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"£" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"$" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"&" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"'" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"{" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"}" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"[" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"]" withString:@"_"]; 
    remover = [remover stringByReplacingOccurrencesOfString:@"""" withString:@"_"]; 

    return remover; 
} 


- (NSString *) audioPathForResource: (NSString *) audio { 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *saveDirectory = [paths objectAtIndex:0]; 
    NSString *newFolder = [saveDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@/Audio",catName]]; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:newFolder]) { 
     [[NSFileManager defaultManager] createDirectoryAtPath:newFolder withIntermediateDirectories:YES attributes:nil error:nil]; 
    } 

    NSString *saveFileName = [NSString stringWithFormat:@"%@.caf",audio]; 
    NSString *newFilePath = [newFolder stringByAppendingPathComponent:saveFileName]; 


    return [newFilePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

} 


- (IBAction)cancelTapped:(id)sender { 

    [self dismissModalViewControllerAnimated:YES]; 

} 

- (IBAction)saveTapped:(id)sender { 


    [self.parentViewController performSelector:@selector(changeAddAudioIcon)]; 

    [self dismissModalViewControllerAnimated:YES]; 

} 


- (IBAction)trashTapped:(id)sender { 

    UIAlertView *alert = 
    [[UIAlertView alloc] initWithTitle: @"Delete" 
           message: @"Would you like to delete the audio file? Warning: This cannot be undone." 
           delegate: self 
        cancelButtonTitle: @"Cancel" 
        otherButtonTitles: @"Delete", nil]; 
    [alert show]; 
    [alert release]; 

} 

- (IBAction)pauseTapped:(id)sender { 

    pauseBtn.enabled = NO; 
    playBtn.enabled = YES; 
    recordBtn.enabled = YES; 
    trashBtn.enabled = YES; 

    if (audioRecorder.recording) 
    { 
     [audioRecorder stop]; 
    } else if (audioPlayer.playing) { 
     [audioPlayer stop]; 
    } 


} 

- (IBAction)recordTapped:(id)sender { 

    if (!audioRecorder.recording) 
    { 
     playBtn.enabled = NO; 
     pauseBtn.enabled = YES; 
     trashBtn.enabled = NO; 
     [audioRecorder record]; 
    } 
} 

- (IBAction)playTapped:(id)sender { 


     pauseBtn.enabled = YES; 
     recordBtn.enabled = NO; 
     trashBtn.enabled = YES; 

     NSError *error; 

     NSLog(@"%@",filepathstring); 


     NSURL *soundFileURL = [NSURL fileURLWithPath:filepathstring]; 

      audioPlayer = [[AVAudioPlayer alloc] 
          initWithContentsOfURL:soundFileURL         
          error:&error]; 


     audioPlayer.delegate = self; 

     if (error) 
      NSLog(@"Error: %@", 
        [error localizedDescription]); 
     else 
      [audioPlayer play]; 


} 



- (void)alertView: (UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { 


    switch (buttonIndex) { 
     case 0: 

      return; 
      break; 
     case 1: 
     { 
      NSError *error = nil; 
      [[NSFileManager defaultManager] removeItemAtPath:filepathstring error:&error]; 
      trashBtn.enabled = NO; 
     } 

      break; 

     default: 
      break; 
    } 

} 

-(void)audioPlayerDidFinishPlaying: 
(AVAudioPlayer *)player successfully:(BOOL)flag 
{ 
    recordBtn.enabled = YES; 
    pauseBtn.enabled = NO; 
    playBtn.enabled = YES; 

    if(player != audioPlayer) { 
     [player release]; 
    } 

} 
-(void)audioPlayerDecodeErrorDidOccur: 
(AVAudioPlayer *)player 
           error:(NSError *)error 
{ 
    NSLog(@"Decode Error occurred"); 
} 
-(void)audioRecorderDidFinishRecording: 
(AVAudioRecorder *)recorder 
          successfully:(BOOL)flag 
{ 

    NSLog(@"Recording success:%@",flag ? @"YES" : @"NO"); 

    trashBtn.enabled = YES; 
    pauseBtn.enabled = NO; 
    playBtn.enabled = YES; 

} 
-(void)audioRecorderEncodeErrorDidOccur: 
(AVAudioRecorder *)recorder 
            error:(NSError *)error 
{ 
    NSLog(@"Encode Error occurred"); 
} 




#pragma mark - View lifecycle 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view from its nib. 





} 

- (void) viewWillAppear:(BOOL)animated { 



    catName = [NSString stringWithFormat:@"%@",[self removeCharsFrom:catName]]; 
    testName = [NSString stringWithFormat:@"%@",[self removeCharsFrom:testName]]; 
    filepathstring = [[self audioPathForResource:testName] retain]; 
    NSLog(@"At start = %@",filepathstring); 

    if ([[NSFileManager defaultManager] fileExistsAtPath:filepathstring]) { 
     playBtn.enabled = YES; 
     trashBtn.enabled = YES; 
     recordBtn.enabled = YES; 
    } 
    else 
    { 
     playBtn.enabled = NO; 
     trashBtn.enabled = NO; 
    } 

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; 


    NSURL *soundFileURL = [NSURL fileURLWithPath:filepathstring]; 

    NSDictionary *recordSettings = [NSDictionary 
            dictionaryWithObjectsAndKeys: 
            [NSNumber numberWithInt:AVAudioQualityMin], 
            AVEncoderAudioQualityKey, 
            [NSNumber numberWithInt:16], 
            AVEncoderBitRateKey, 
            [NSNumber numberWithInt: 2], 
            AVNumberOfChannelsKey, 
            [NSNumber numberWithFloat:44100.0], 
            AVSampleRateKey, 
            nil]; 

    NSError *error = nil; 

    audioRecorder = [[AVAudioRecorder alloc] 
        initWithURL:soundFileURL 
        settings:recordSettings 
        error:&error]; 

    audioRecorder.delegate = self; 

    if (error) 
    { 
     NSLog(@"error: %@", [error localizedDescription]); 

    } else { 
     [audioRecorder prepareToRecord]; 
    } 

} 

- (void)viewDidUnload 
{ 
    [self setCancelBtn:nil]; 
    [self setSaveBtn:nil]; 
    [self setTimeLabel:nil]; 
    [self setDescriptionLabel:nil]; 
    [self setToolsBar:nil]; 
    [self setTrashBtn:nil]; 
    [self setPauseBtn:nil]; 
    [self setRecordBtn:nil]; 
    [self setPlayBtn:nil]; 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    // Return YES for supported orientations 
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { 
     return YES; 
    } else { 
     return UIInterfaceOrientationIsPortrait(interfaceOrientation); 
    } 
} 

- (void)dealloc { 
    [cancelBtn release]; 
    [saveBtn release]; 
    [timeLabel release]; 
    [descriptionLabel release]; 
    [toolsBar release]; 
    [trashBtn release]; 
    [pauseBtn release]; 
    [recordBtn release]; 
    [playBtn release]; 
    [audioPlayer release]; 
    [audioRecorder release]; 
    [super dealloc]; 
} 
+0

如果你在前面的代碼示例中的每一行有四個空格,將正確顯示在這裏。 – JoeZuntz 2012-01-17 17:25:26

+0

我發現[audioPlayer play]返回NO。這雖然沒有給我提供任何錯誤或者任何東西,但是......無論如何獲得更多關於它爲什麼不能玩的信息? – HarryGT 2012-01-18 13:44:52

+0

的NSData到的NSFileManager .....但創建.mp3音頻文件無法播放 – 2014-09-26 11:17:34

回答

0

這裏是答案:

NSData *data = [NSData dataWithContentsOfMappedFile:[NSString stringWithFormat:@"%@",filepathstring]]; 


    AVAudioPlayer *ap = [[AVAudioPlayer alloc] 
        initWithData:data error:&error]; 

似乎它只是不會與filepathstring工作,但在NSString內工作正常。現在明顯!