2015-11-09 42 views
2

類中AVAudioPlayer要整理東西播放音頻,我決定創建一個名爲的SoundPlayer所在班級從我的應用程序運行的所有音頻文件。 (這將避免很多重複的代碼)與NSObject的

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類中的所有代碼複製並放入我將使用的課程中,則聲音完美運行)問題是什麼?

回答

4

您的SoundPlayer班正在超出範圍並被釋放,從而使聲音沉默。

其分配給成員變量在您的應用程序代理:

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

謝謝您。它的工作真棒。 – Raja

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