-(IBAction)test1
{
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef =CFBundleCopyResourceURL(mainBundle,
(CFStringRef) @"Bear3", CFSTR ("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef , &soundID);
AudioServicesPlaySystemSound(soundID);
AudioServicesDisposeSystemSoundID(soundID);
CFRelease(soundFileURLRef);
}
它没有播放声音文件
答案 0 :(得分:3)
您的代码无效,因为您在完成资源之前会将资源丢弃。
AudioServicesDisposeSystemSoundID(soundID);
播放声音时不应调用。您需要重新组织代码。
如果更高级CF
类可以完成这项工作,您还应该避免使用NS
类。在这种情况下,他们可以。方法如下:
回应评论的代码: SoundExampleViewController.h:
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
@interface SoundExampleViewController : UIViewController{
SystemSoundID bear3SoundID;
}
-(IBAction)playSoundButtonPushed:(id)sender;
@end
SoundExampleViewController.m:
#import "SoundExampleViewController.h"
@implementation SoundExampleViewController
-(IBAction)playSoundButtonPushed:(id)sender{
AudioServicesPlaySystemSound(bear3SoundID);
}
- (void)viewDidLoad{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"Bear3" ofType:@"wav"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&bear3SoundID);
}
- (void)viewDidUnload{
[super viewDidUnload];
AudioServicesDisposeSystemSoundID(bear3SoundID);
}
@end
即使您坚持使用CF
方法中的viewDidLoad
类,也应遵循此常规布局。