【问题标题】:Audio file not play in objective C音频文件无法在目标 C 中播放
【发布时间】:2017-03-31 06:10:01
【问题描述】:
- (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];
}
【问题讨论】:
标签:
ios
objective-c
ios10
【解决方案1】:
与其转换成 NSData,不如将 URL 传递给 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];
【解决方案2】:
您的代码运行良好。问题出在您尝试记录数据时。
或者尝试使用initWithContentsOfURL 方法。
#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];
}