gpt4 book ai didi

ios - 在 NSObject 类中使用 AVAudioPlayer 播放音频

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:25:29 24 4
gpt4 key购买 nike

为了组织事情,我决定创建一个名为 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

声音播放器.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 类超出范围并被释放,这使声音静音。

将其分配给应用委托(delegate)中的成员变量:

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

关于ios - 在 NSObject 类中使用 AVAudioPlayer 播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33601870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com