我正在尝试为iOS 8学习新的CoreAudio API,但似乎无法在我的设备上生成任何声音。我正在使用WWDC会话502中的代码加上我认为开始音频会话是个好主意。
#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions {
// Override point for customization after application launch.
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error;
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
AVAudioEngine *engine = [[AVAudioEngine alloc] init];
AVAudioPlayerNode *player = [[AVAudioPlayerNode alloc] init];
[engine attachNode:player];
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"mySound" withExtension:@"aif"];
AVAudioFile *file = [[AVAudioFile alloc] initForReading:fileURL error:&error];
if (error) {
NSLog(@"error getting audio file");
}
AVAudioMixerNode *mainMixer = [engine mainMixerNode];
// just to be safe
mainMixer.outputVolume = 1;
[engine connect:player to:mainMixer format:file.processingFormat];
[player scheduleFile:file atTime:nil completionHandler:nil];
if ([engine startAndReturnError:&error]) {
NSLog(@"engine succsessful %@", error);
} else {
NSLog(@"error starting engine: %@", error);
}
[player play];
return YES;
}
我错过了什么?
谢谢!
答案 0 :(得分:3)
engine
在你听到任何声音之前就会被释放。添加引擎作为类成员,因此一旦didFinishLaunching返回它就不会被抛弃
#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
@interface AppDelegate ()
AVAudioEngine *engine;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions {
// Override point for customization after application launch.
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error;
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
engine = [[AVAudioEngine alloc] init];
AVAudioPlayerNode *player = [[AVAudioPlayerNode alloc] init];
[engine attachNode:player];
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"mySound" withExtension:@"aif"];
AVAudioFile *file = [[AVAudioFile alloc] initForReading:fileURL error:&error];
if (error) {
NSLog(@"error getting audio file");
}
AVAudioMixerNode *mainMixer = [engine mainMixerNode];
// just to be safe
mainMixer.outputVolume = 1;
[engine connect:player to:mainMixer format:file.processingFormat];
[player scheduleFile:file atTime:nil completionHandler:nil];
if ([engine startAndReturnError:&error]) {
NSLog(@"engine succsessful %@", error);
} else {
NSLog(@"error starting engine: %@", error);
}
[player play];
return YES;
}
AVAudioSession是不必要的。