问题描述
为了整理事物,我决定创建一个名为 SoundPlayer 的类,该类将运行我的应用程序中的所有音频文件. (这样可以避免有很多重复的代码)
To organize things , I decided to create a class called SoundPlayer where will run all audio files from my app. (This would avoid having many duplicate codes)
SoundPlayer.h
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
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 内部调用此类,如下所示:
This code is very simple, and seems to work great. When the user open my app for first time I want to play a sound, for this I call this class inside didFinishLaunchingWithOptions, like this:
- (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 类中的所有代码并将其放到我将要使用的类中,则声音运行得很好)是什么问题?
The problem is that the sound is not being executed (Now, if I copied all the code within the SoundPlayer class and put into the class I would use, the sound runs perfectly) what's the problem ?
推荐答案
您的SoundPlayer
类超出范围并被释放,从而使声音静音.
Your SoundPlayer
class is going out of scope and being deallocated, which silences the sound.
将其分配给您的应用程序委托中的成员变量:
Assign it to a member variable in your app delegate:
self.sound = [[SoundPlayer alloc] init];
[sound PlaySound:@"preview" extension:@"mp3" loops:0];
这篇关于使用NSObject类中的AVAudioPlayer播放音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!