没有声音在播放

时间:2011-11-08 19:50:17

标签: iphone ios4 memory audio

-(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);
}

它没有播放声音文件

1 个答案:

答案 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类,也应遵循此常规布局。