在NSObject类中使用AVAudioPlayer播放audio

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

SoundPlayer.h

#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 

SoundPlayer.m

 #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 

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

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { SoundPlayer *sound = [[SoundPlayer alloc] init]; [sound PlaySound:@"preview" extension:@"mp3" loops:0]; return YES;//Diz que o retorno esta ok! } 

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

您的SoundPlayer类将超出范围并被释放,从而使声音沉默。

将其分配给您的应用程序委托中的成员variables:

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

试试这个:

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; }