Search code examples
iphoneiosios6avaudioplayeravaudiorecorder

After recording audio and save to document directory unable to play audio file with AVAudioPlayer


I'm working on application which has record audio and play that recorded file which is store in document directory.

Here is my code:

Record button method.

(IBAction)stopButtonPressed:(id)sender{

     UIButton *button = (UIButton *)sender;

     if (button.selected) { // Play recorded file.

     self.stopButton.selected = NO;

     NSError *error;

    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioRecorder.url     error:&error];

    self.audioPlayer.delegate = self;

    self.audioPlayer.volume = 1.0;

    [self.audioPlayer prepareToPlay];

    [self.audioPlayer play];

    }

    else{ // Stop recording.

    self.stopButton.selected = YES;

    if (recordTimer) {

    [recordTimer invalidate];

    }

    [self.audioPlayer stop];

    self.recordButton.selected = NO;

    [audioRecorder stop];

    self.readyLabel.text = @"READY";

    [self insertNewRecording];
        }
    }

Solution

  • um..I am not sure. But as a test, maybe you can try if you can play the file by specifying its name? E.g. you got a forest.mp3 to play and the key part of the code can be like this:

    path = [[NSBundle mainBundle] pathForResource:@"forest" ofType:@"mp3"]; 
    NSData *sampleData = [[NSData alloc] initWithContentsOfFile:path]; 
    NSError *audioError = nil; 
    av = [[AVAudioPlayer alloc] initWithData:sampleData  error:&audioError];
    

    If everything went well, maybe it's something to do with audioRecorder.url in your code?

    Hope this gives you some ideas.