我正在尝试学习新的CoreAudio iOS 8的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;}
我遗漏了什么?
谢谢!
发布于 2014-06-14 20:20:31
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是不必要的。
https://stackoverflow.com/questions/24223111
复制相似问题