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

use*_*331 2 audio xcode objective-c avaudioplayer ios

我在 iOS 9 上使用 XCode 7,我正在尝试播放声音。我一直在谷歌上搜索解决方案好几天了,我已经尝试了所有可能的解决方案,但没有任何效果。

这是我的代码

。H

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

@interface ViewController : UIViewController <DTDeviceDelegate, AVAudioPlayerDelegate>
{

}
Run Code Online (Sandbox Code Playgroud)

这是我的 .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];
Run Code Online (Sandbox Code Playgroud)

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

soundFilePath并且soundFileURL不是nil,与玩家一样,他们越来越多。我的电话音量尽可能大。

我也在 .m 文件中尝试过:

@property(strong, nonatomic) AVAudioPlayer *player;

self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
[self.myPlayer play];
Run Code Online (Sandbox Code Playgroud)

也没有播放声音,也没有错误。

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

在此处输入图片说明

请帮忙!

Bas*_*ash 5

将 AVAudioPlayer 定义为一个属性,它应该可以工作。如果需要,您可以实现 AVAudioPlayerDelegate,这不是必须的。

有关详细说明,请查看此答案/sf/answers/589106171/

@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);
}
Run Code Online (Sandbox Code Playgroud)