2012-01-17 34 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内工作正常。现在明显!