实用知识:音乐播放的方法使用

来源:互联网 发布:php 面相过程 编辑:程序博客网 时间:2024/06/05 09:59
#import "ViewController.h"#import <AVFoundation/AVFoundation.h>@interface ViewController () <AVAudioPlayerDelegate>// 音乐播放类@property (strong, nonatomic) AVAudioPlayer *player;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    NSURL *url = [[NSBundle mainBundle] URLForResource:@"ABC.mp3" withExtension:nil];    NSError *error;    // URL是只读的, 不能修改, AVAudioPlayer只对应一首歌曲    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];    _player.delegate = self;    if (error) {        NSLog(@"%@", error);    }    // 做数据缓存 / 硬件准备    [_player prepareToPlay];    NSLog(@"总时长: %f秒", _player.duration);}- (IBAction)playBtnAction:(id)sender{    // 当前播放时间    _player.currentTime = 30;    // 如果没有prepare, 则play方法会隐式的去调用 prepareToPlay    [_player play];}- (IBAction)pauseBtnAction:(id)sender{    if (_player.isPlaying) {        // 暂停播放        [_player pause];    } else {        [_player play];    }}- (IBAction)stopBtnAction:(id)sender{    // 重置currentTime    _player.currentTime = 0;    // 停止播放, 清空数据缓存, 释放硬件准备    [_player stop];}#pragma mark - AVAudioPlayerDelegate// 歌曲播放完成触发- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{    if (flag == YES) {        NSLog(@"正常播放完成");    }}// 解码歌曲文件失败时触发- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{    NSLog(@"解码失败");}@end
0 0