-1
- (void)play {
    NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"sound" withExtension:@"mp3"];
    NSString *path = [imgPath path];
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
    NSLog(@"%@",data);
    NSError *error;   
    self.avPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
    [self.avPlayer play];
    }
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103

2 Answers2

1

Rather then converting into NSData, you can pass URL to AVAudioPlayer.

    NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"sound" withExtension:@"mp3"];

    NSError *error;

    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:imgPath
                                                         error:&error];
    self.player.numberOfLoops = 0; //Infinite
    self.player.delegate  = self;
    [self.player prepareToPlay];
    [self.player play];
Hiren Patel
  • 190
  • 7
0

Your code works fine. The problem is while you try to Log the Data. Or else try with initWithContentsOfURL method.

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>


@interface ViewController ()

@property (nonatomic, strong) AVAudioPlayer *avPlayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"1" withExtension:@"mp3"];

    NSString *path = [imgPath path];

    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];

   // NSLog(@"%@",data);

    NSError *error;

    self.avPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];

 //   self.avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:imgPath error:&error];

    [self.avPlayer play];


}
NITHI CHAN
  • 56
  • 2