使用AudioToolBox播放声音文件但没有声音的类

时间:2014-03-06 04:21:09

标签: objective-c xcode audiotoolbox

我有两个类,我正在初始化SystemSoundID,然后在一个链接到实际声音文件的方法中。 但是当我调用MainViewController中的方法并通过IBAction播放时,没有声音播放。

Sound.h:

    #import <Foundation/Foundation.h>
    #import <AudioToolbox/AudioServices.h>

    @interface TheSound : NSObject {
        SystemSoundID yayFileID;
    }
    @property(nonatomic) SystemSoundID yayFileID;
    - (void) initSound;

    @end

Sound.m:

    #import "TheSound.h"
    #import <AudioToolbox/AudioServices.h>

    @implementation TheSound
    @synthesize yayFileID;

    - (void) initSound {
        NSString *yayPath = [[NSBundle mainBundle] pathForResource: @"yay" ofType: @"wav"];
        CFURLRef yayURL = (__bridge CFURLRef) [NSURL fileURLWithPath:yayPath];
        AudioServicesCreateSystemSoundID(yayURL, &yayFileID);
    }

    @end

MainViewController.h:

    #import <UIKit/UIKit.h>
    #import "TheSound.h"

    @interface MainViewController : UIViewController

    - (IBAction) playSound: (id) sender;

    @end

MainViewController.m:

    #import "MainViewController.h"
    #import <AudioToolbox/AudioServices.h>
    #import "TheSound.h"

    @interface MainViewController ()
    @property SystemSoundID yayFileID;
    @property (nonatomic) TheSound *foo;
    @end

    @implementation MainViewController
    @synthesize foo;

    - (void)viewDidLoad {
        [foo initSound];
        [super viewDidLoad];
    }


    - (IBAction)playSound:(id)sender {
        AudioServicesPlaySystemSound(_yayFileID);
    }

    @end

非常感谢帮助我做错了什么!提前谢谢!

1 个答案:

答案 0 :(得分:0)

下面

- (IBAction)playSound:(id)sender {
    AudioServicesPlaySystemSound(_yayFileID);
}

变量_yayFileID是指MainViewController中与yayFileID对象中的TheSound变量完全无关的变量。

也许你试试

AudioServicesPlaySystemSound(foo.yayFileID);

即使你这样做,我认为它不会起作用,因为另外,你的foo变量没有被初始化,所以调用initSound被发送到null。你应该做这样的事情

foo = [[TheSound alloc] init];
[foo initSound];