音频文件无法在目标 C 中播放
Posted
技术标签:
【中文标题】音频文件无法在目标 C 中播放【英文标题】:Audio file not play in objective 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];
【问题讨论】:
【参考方案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];
【讨论】:
另外,请确保您进行了正确的导入:#import #import 参考:- ***.com/a/11528463【参考方案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];
【讨论】:
以上是关于音频文件无法在目标 C 中播放的主要内容,如果未能解决你的问题,请参考以下文章