如何在AVAudioPlayer播放器对象中子类或存储额外信息

时间:2012-06-08 22:44:33

标签: iphone objective-c ios avaudioplayer subclassing

我需要创建一个名为primaryKey的新NSNumber或整数属性,以包含在我创建的所有AVAudioPlayer个对象中,以便我可以在audioPlayerDidFinishPlaying中读取该属性的值回调并确切地知道播放了哪个数据库记录。

我需要这样做的原因是:我无法使用播放器URL property来确定它是哪个数据库记录,因为在播放列表中可以多次使用相同的声音文件。

如何将新属性添加到现有的iOS类中?


示例:

AVAudioPlayer *newAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];  

self.theAudio = newAudio; // automatically retain audio and dealloc old file if new file is loaded
if (theAudio != nil) [audioPlayers addObject:theAudio];

[newAudio release];

[theAudio setDelegate: theDelegate];
[theAudio setNumberOfLoops: 0];
[theAudio setVolume: callVolume];

// This is the new property that I want to add
[theAudio setPrimaryKey: thePrimaryKey];

[theAudio play];

然后我会在回调中检索它,如下所示:

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag 
{    
   NSNumber *finishedSound = [NSNumber numberWithInt:[player primaryKey]];

   // Do something with this information now...
}

2 个答案:

答案 0 :(得分:3)

您可以创建子类并添加属性,就像子类化任何内容一样。

接口

@interface MyAudioPlayer : AVAudioPlayer

@property (nonatomic) int primaryKey;

@end

实施

@implementation MyAudioPlayer

@synthesize primaryKey = _primaryKey;

@end

创建

MyAudioPlayer *player = [[MyAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.primaryKey = thePrimaryKey;
...

代表

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    if ([player isKindOfClass:[MyAudioPlayer class]]) {
        MyAudioPlayer *myPlayer = (MyAudioPlayer *)player;
        NSNumber *primaryKeyObject = [NSNumber numberWithInt:myPlayer.primaryKey];
        ...
    }
}

答案 1 :(得分:1)

一种简单的方法可能是创建一个NSMutableDictionary并使用您创建的AVAudioPlayers作为KEYS,主键(或整个字典)作为相应的VALUE。然后,当玩家停止播放(或错误)时,您可以在字典中查找并恢复任何您喜欢的内容。