- (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];
}
Asked
Active
Viewed 316 times
-1

Suraj Rao
- 29,388
- 11
- 94
- 103

Vinay Kumar
- 1
- 2
2 Answers
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
-
Also, make sure you do the proper imports: #import
#import – Rajesh Dharani Mar 31 '17 at 07:46For Ref:- http://stackoverflow.com/a/11528463
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