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