在NSObject类中使用AVAudioPlayer播放音频

时间:2015-11-09 03:02:14

标签: ios objective-c avaudioplayer nsobject

为了组织事情,我决定创建一个名为 SoundPlayer 的类,其中将运行我的应用程序中的所有音频文件。 (这将避免有许多重复的代码)

SoundPlayer.h

StackOverflowException

SoundPlayer.m

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

@interface SoundPlayer : NSObject <AVAudioPlayerDelegate>

@property (strong,nonatomic) AVAudioPlayer *backgroundMusicPlayer;

-(void)PlaySound:(NSString*)name extension:(NSString*)ext loops:(int)val;

@end

这段代码非常简单,而且效果很好。当用户第一次打开我的应用程序时我想播放声音,为此我在 didFinishLaunchingWithOptions 中调用此类,如下所示:

#import "SoundPlayer.h"

@implementation SoundPlayer

-(void)PlaySound:(NSString *)name extension:(NSString *)ext loops:(int)val{

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:name ofType:ext];
    NSURL *soundPath = [[NSURL alloc] initFileURLWithPath:soundFilePath];
    NSError *error;
    self.backgroundMusicPlayer = [[AVAudioPlayer alloc]
                                  initWithContentsOfURL:soundPath error:&error];
    self.backgroundMusicPlayer.numberOfLoops = val;
    [self.backgroundMusicPlayer prepareToPlay];
    [self.backgroundMusicPlayer play];
}

@end

问题是声音没有被执行(现在,如果我复制了 SoundPlayer 类中的所有代码并放入我将使用的类中,声音运行完美)问题是什么?

2 个答案:

答案 0 :(得分:4)

你的SoundPlayer课程已经超出范围并被解除分配,这使声音无声。

将其分配给应用代理中的成员变量:

self.sound = [[SoundPlayer alloc] init];
[sound PlaySound:@"preview" extension:@"mp3" loops:0];

答案 1 :(得分:1)

试试这个:

AppDelegate.h

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

 @interface AppDelegate : UIResponder <UIApplicationDelegate>
   @property (strong, nonatomic) UIWindow *window;
   @property(strong,nonatomic) SoundPlayer * soundPlayer;
@end

AppDelegate.m

#import "AppDelegate.h"
#import "SoundPlayer.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.soundPlayer = [[SoundPlayer alloc] init];
    [self.soundPlayer PlaySound:@"preview" extension:@"mp3" loops:0];
    return YES;
}