将类用作静态AVAudioPlayer的AVAudioPlayerDelegate

时间:2013-04-15 04:41:46

标签: ios objective-c delegates avaudioplayer trigger.io

我无法在TriggerIO插件中维护一个实例,因此我需要一种静态的方式来响应我的AVAudioPlayer事件。但是,我无法将player.delegate设置为audio_API,所以我有点卡住了。

audio_API.h:

@interface audio_API : NSObject<AVAudioPlayerDelegate>

audio_API.m:

static AVAudioPlayer* player = nil;


@implementation audio_API


+ (void)play:(ForgeTask*)task {

    // parse the file url from the file object
    ForgeFile* file = [[ForgeFile alloc] initWithFile:[task.params objectForKey:@"file"]];
    NSString* fileURL = [file url];

    NSLog(@"Playing file at %@", fileURL);

    NSURL* url = [NSURL URLWithString:fileURL];


    // TESTING
    url = [[NSBundle mainBundle] URLForResource:@"seconds.m4a" withExtension:nil];
    // END TESTING

    NSAssert(url, @"URL is invalid.");

    // create the player
    NSError* error = nil;
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    if(!player)
    {
        NSLog(@"Error creating player: %@", error);
    };

//    player.delegate = audio_API;

    [player play];

    [task success:nil];
}


+ (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (flag) {
        [ForgeLog d:@"Audio finished playing successfully."];
    } else {
        [ForgeLog d:@"Audio did not finish playing successfully."];
    }

    // call the audio.finishedPlaying event
    [[ForgeApp sharedApp] event:@"audio.finishedPlaying" withParam:nil];
}

+ (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
    [ForgeLog d:@"Audio had error decoding."];
    [ForgeLog e:error];

    // call the audio.decodeErrorOccurred event
    [[ForgeApp sharedApp] event:@"audio.decodeErrorOccurred" withParam:nil];
}

@end

有关如何使这项工作的想法吗?

感谢。

2 个答案:

答案 0 :(得分:3)

委托必须是对象,但audio_API是类型名称。但是,您可以简单地将委托指定为audio_API

的类对象
player.delegate = (id<AVAudioPlayerDelegate>)[audio_API class];

注意:如果你没有强制转换类对象,编译器会抱怨,因为[audio_API class]返回Class而不是Class<AVAudioPlayerDelegate>,即使你在界面上指定了委托audio_API

答案 1 :(得分:0)

对我来说,这有助于使管理声音的类成为AVAudioPlayerDelegate。 SoundManager.h文件:

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>

@interface SoundManager : NSObject<AVAudioPlayerDelegate> {

}

,并且在.m文件中,您可以选择为委托实现回调,例如:

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"audioPlayerDidFinishPlaying %d",flag);
}