3

I am using XCode 7 with iOS 9 and I am trying to play a sound. I have been googling for a solution for days and I have tried every possible solution out there and nothing is working.

Here is my code

.h

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

@interface ViewController : UIViewController <DTDeviceDelegate, AVAudioPlayerDelegate>
{

}

and here is my .m file:

 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];

and no sound, no errors, no warnings nothing at all

soundFilePath and soundFileURL are not nil, same with player, they are getting populated. My phone volume is as loud as it can be.

I have also tried in .m file:

@property(strong, nonatomic) AVAudioPlayer *player;

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

Also did not play sound and no errors.

Here is a screenshot of my Resources folder:

enter image description here

Please Help!

Gosha A
  • 4,520
  • 1
  • 25
  • 33
user979331
  • 11,039
  • 73
  • 223
  • 418

2 Answers2

5

Define AVAudioPlayer as a property, and it should work. You could implement the AVAudioPlayerDelegate if you want, its not a must.

For detailed explanation check this answer https://stackoverflow.com/a/8415802/1789203

@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);
}
Bassl Kokash
  • 627
  • 5
  • 10
  • I believe numberOfLoops = 0 means play once. If you want infinite playback so any negative number as documented here by Apple https://developer.apple.com/reference/avfoundation/avaudioplayer/1386071-numberofloops – saintjab Nov 11 '16 at 21:53
0

You need to set delegate to self before [player play];

player.delegate  = self;
[player play];
Idali
  • 1,023
  • 7
  • 10