【问题标题】:How to subclass or store extra information in AVAudioPlayer player objects如何在 AVAudioPlayer 播放器对象中继承或存储额外信息
【发布时间】:2012-06-08 22:44:33
【问题描述】:

我需要创建一个名为 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...
}

【问题讨论】:

    标签: iphone objective-c ios avaudioplayer subclassing


    【解决方案1】:

    您可以创建一个子类并添加您的属性,就像对任何东西进行子类化一样。

    界面

    @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];
            ...
        }
    }
    

    【讨论】:

    • 谢谢罗伯!这正是我希望你能做到的。我仍在学习子类化,但这很有意义:)
    • 快速提问:为什么我不能直接使用- (void)audioPlayerDidFinishPlaying:(MyAudioPlayer *)player,这样我就不必将播放器投射到MyAudioPlayer 对象中?
    • 你可以,如果你确定该消息的接收者只是MyAudioPlayer对象的代表,而不是普通AVAudioPlayer对象的代表。
    【解决方案2】:

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

    【讨论】:

    • 感谢您的帮助,但我不想创建管理其他字典的额外工作。
    • 很公平,但管理字典似乎比创建新子类更容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多