【问题标题】:AVAudioPlayer isPlaying crashing appAVAudioPlayer 正在播放崩溃的应用程序
【发布时间】:2010-10-04 19:23:15
【问题描述】:

我正在使用 AVAudioPlayer 来管理一些声音,但 isPlaying 方法似乎崩溃了。

在我启动页面时完成:

self.soundClass = [AVAudioPlayer alloc];

我如何播放声音:

-(void)playSound:(NSString *)fileName:(NSString *)fileExt {

    if ( [self.soundClass isPlaying] ){
        [self.soundClass pause];
    }
    else if (newSoundFile == currentSoundFile) {
        [self.soundClass play];
    }
    else {
        NSLog(@"PlaySound with two variable passed function");
        [[NSBundle mainBundle] pathForResource: fileName ofType:fileExt]], &systemSoundID);

        [self.soundClass initWithContentsOfURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource: fileName ofType:fileExt]] error:nil];

        [self.soundClass prepareToPlay];
        [self.soundClass play];
    }

    self.currentSoundFile = fileName;

}

我的 soundClass 现在很空:

声音类.h

#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import<AVFoundation/AVFoundation.h>


@interface SoundClass : AVAudioPlayer <AVAudioPlayerDelegate> {

}

@end

SoundClass.m

#import "SoundClass.h"

@implementation SoundClass 
-(void)dealloc {


    [super dealloc];
}

@end

你有没有看到我可能做错了什么?它在if ( isPlaying ) 处崩溃

【问题讨论】:

    标签: objective-c xcode ipad ios4


    【解决方案1】:

    您在列出的第一行中指向为 AVAudioPlayer 实例分配的空间,但实际上并未初始化实例。在 Cocoa 中,“alloc”有 99.9% 的时间后跟某种形式的 -init(如 -initWithContentsOfURL:error: 在 AVAudioPlayer 的情况下)。

    此外,“soundClass”是一个实例变量的奇怪名称。您应该阅读类(对象的蓝图)和类的实例(从蓝图构建的实际对象)之间的区别。扎实掌握这一概念对于您理解 Cocoa(以及所有面向对象的)编程至关重要。

    【讨论】:

    • 嗯,当我开始并且程序还没有被告知要播放什么时,我可以什么都没有初始化吗?还是我应该加载一些东西?如果我要更改剪辑,我是否只需重新初始化WithContentsOfURL?
    • 在这种情况下,将其设置为 nil。这通常在您的类的 init... 方法中完成(“self”在这种情况下指向的实例的类)。
    • 所以 self.soundClass = nil?这不是设置删除吗?
    • "soundClass" 是一个属性 - 一个指向实例变量的指针。如果一个对象被分配给它并且你将它设置为 nil(并且没有其他东西对它有“兴趣”),那么那个对象会消失,但你的指针仍然存在(并且指向 nil 直到你告诉它)。
    • 嗯,很有趣。虽然没有修好。我不断收到 EXC_BAD_ACCESS 信号。不太确定我如何找到有关该错误的更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    相关资源
    最近更新 更多