I'm attempting to play an AVAudioFile using the AVAudioEngine. The code is largely taken and adapted from the Apple Developer on-line videos, but there is no playback. Have spent some time going through the forums, but nothing seems to throw any light on it.
I have two methods. The first one calls the standard open file dialog, opens the audio file, allocates an AVAudioBuffer object (which I will use later) and fills it with the audio data. The second one sets up the AVAudioEngine and AVAudioPlayerNode objects, connects everything up and plays the file. The two methods are listed below .
- (IBAction)getSoundFileAudioData:(id)sender {
NSOpenPanel* openPanel = [NSOpenPanel openPanel];
openPanel.title = @"Choose a .caf file";
openPanel.showsResizeIndicator = YES;
openPanel.showsHiddenFiles = NO;
openPanel.canChooseDirectories = NO;
openPanel.canCreateDirectories = YES;
openPanel.allowsMultipleSelection = NO;
openPanel.allowedFileTypes = @[@"caf"];
[openPanel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
NSURL* theAudioFileURL = [[openPanel URLs] objectAtIndex:0];
// Open the document.
theAudioFile = [[AVAudioFile alloc] initForReading:theAudioFileURL error:nil];
AVAudioFormat *format = theAudioFile.processingFormat;
AVAudioFrameCount capacity = (AVAudioFrameCount)theAudioFile.length;
theAudioBuffer = [[AVAudioPCMBuffer alloc]
initWithPCMFormat:format frameCapacity:capacity];
NSError *error;
if (![theAudioFile readIntoBuffer:theAudioBuffer error:&error]) {
NSLog(@"problem filling buffer");
}
else
playOrigSoundFileButton.enabled = true;
}
}];}
- (IBAction)playSoundFileAudioData:(id)sender {
AVAudioEngine *engine = [[AVAudioEngine alloc] init]; // set up the audio engine
AVAudioPlayerNode *player = [[AVAudioPlayerNode alloc] init]; // set up a player node
[engine attachNode:player]; // attach player node to engine
AVAudioMixerNode *mixer = [engine mainMixerNode];
[engine connect:player to:mixer format:theAudioFile.processingFormat]; // connect player node to mixer
[engine connect:player to:mixer format:[mixer outputFormatForBus:0]]; // connect player node to mixer
NSError *error;
if (![engine startAndReturnError:&error]) {
NSLog(@"Problem starting engine ");
}
else {
[player scheduleFile:theAudioFile atTime: nil completionHandler:nil];
[player play];
}
}
I have checked that the functions are being executed, that the audio engine is running and the audio file has been read. I have also tried with different audio file formats, both mono and stereo. Any ideas?
I'm running Xcode 7.3.1.
declare your AVAudioPlayerNode *player
as global
refer this link Can't play file from documents in AVAudioPlayer