本文共 1612 字,大约阅读时间需要 5 分钟。
Objective-C实现音频播放器
以下是一个使用AVFoundation框架创建简单Objective-C音频播放器的示例,包含播放、暂停和停止功能。
在你的Xcode项目中添加AVFoundation框架
在项目的Build Phases中,找到Link Binary With Libraries选项,并将AVFoundation.framework添加到项目中。
完整代码示例
首先,确保在Xcode项目中添加了AVFoundation框架。在项目的Build Phases中,找到Link Binary With Libraries选项,并将AVFoundation.framework添加到项目中。
以下是完整的代码示例:
#import#import @interface PlayerViewController : UIViewController@property (nonatomic, strong) AVAudioPlayer *player;@property (nonatomic, strong) IBOutlet UIButton *playButton;@property (nonatomic, strong) IBOutlet UILabel *currentTimeLabel;@property (nonatomic, strong) IBOutlet UILabel *durationLabel;@end@implementation PlayerViewController- (void)loadView{ [super loadView]; // 初始化播放器 self.player = [[AVAudioPlayer alloc] init]; // 初始化UI [self setupUI];}- (void)setupUI{ [self.view addSubview:self.playButton]; [self.view addSubview:self.currentTimeLabel]; [self.view addSubview:self.durationLabel];}- (IBAction)playButtonTouched:(id)sender{ if ([self.player isPlaying]) { [self.player pause]; [self.playButton setTitle:@"播放" forState:UIControlStateNormal]; } else { [self.player play]; [self.playButton setTitle:@"暂停" forState:UIControlStateNormal]; }}- (void)updateTime{ // 定期更新播放时间 [self.player updateTime]; self.currentTimeLabel.text = [self.player currentTime-description]; self.durationLabel.text = [self.player duration(description)];}@end
注意事项
通过以上代码示例,你可以轻松创建一个基本的Objective-C音频播放器,支持播放、暂停和停止功能。
转载地址:http://iqifk.baihongyu.com/