Objective-C无法使用AVAudioPlayer播放声音

3

我正在使用iOS 9的XCode 7,试图播放声音。我已经搜索了多天,尝试了各种可能的解决方案,但没有一个是有效的。

这是我的代码:

.h

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController <DTDeviceDelegate, AVAudioPlayerDelegate>
{

}

这是我的.m文件:

 NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"autumn_leaves" ofType:@"m4a"];

    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

    NSError *error;

    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
                                                                   error:&error];
    player.numberOfLoops = -1; //Infinite

    [player play];

没有声音,没有错误,没有警告,什么都没有。

soundFilePathsoundFileURL不是nil,与播放器一样被填充。我的手机音量已经尽可能地调到最大了。

我还尝试在.m文件中:

@property(strong, nonatomic) AVAudioPlayer *player;

self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
[self.myPlayer play];

同时没有播放声音也没有错误信息。

这是我的资源文件夹的截图:

在此输入图片描述

请帮忙!


尝试使用 .caf 文件而不是其他类型的文件。这对我有用。 - Vladimir Despotovic
2个回答

5

将AVAudioPlayer定义为属性,就可以使用了。如果需要,您可以实现AVAudioPlayerDelegate,但这不是必须的。

有关详细说明,请查看此答案:https://dev59.com/qWsz5IYBdhLWcg3wQFi2#8415802

@interface ViewController ()
@property (nonatomic,strong)AVAudioPlayer *player;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"bush_god_bless" ofType:@"wav"];

    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

    NSError *error;

    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
                                                                   error:&error];
    self.player.numberOfLoops = 0; //Infinite
    self.player.delegate  = self;
    [self.player play];


}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"%d",flag);
}

我相信 numberOfLoops = 0 意味着播放一次。如果您想要无限循环播放,请使用任何负数,如 Apple 在此处所述:https://developer.apple.com/reference/avfoundation/avaudioplayer/1386071-numberofloops - saintjab

0

在 [player play] 之前,您需要将代理设置为 self。

player.delegate  = self;
[player play];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接