AVAudioPlayer 音频播放

前言

  • Objective-C

    1
    NS_CLASS_AVAILABLE(10_7, 2_2) @interface AVAudioPlayer : NSObject
  • Swift

    1
    @available(iOS 2.2, *) public class AVAudioPlayer : NSObject
  • 本地音乐播放:

    • 添加库文件:AVFoundation.framework
    • 包含头文件:#import <AVFoundation/AVFoundation.h>

1、本地音乐播放

  • Objective-C

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    // 添加库文件:AVFoundation.framework
    // 包含头文件:#import <AVFoundation/AVFoundation.h>

    // 声明音乐播放控件,必须声明为全局属性变量,否则可能不会播放,AVAudioPlayer 只能播放本地音乐
    @property(nonatomic, retain)AVAudioPlayer *musicPlayer;

    // 获取音乐文件路径
    NSURL *musicUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"蓝莲花" ofType:@"mp3"]];

    // 实例化音乐播放控件
    musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicUrl error:nil];

    // 准备(缓冲)播放
    [musicPlayer prepareToPlay];

    // 开始播放音乐
    [musicPlayer play];
  • Swift

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    // 添加库文件:AVFoundation.framework
    // 包含头文件:import AVFoundation

    // 声明音乐播放控件,必须声明为全局属性变量,否则可能不会播放,AVAudioPlayer 只能播放本地音乐
    var musicPlayer: AVAudioPlayer!

    // 获取音乐文件路径
    let musicUrl = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("蓝莲花", ofType: "mp3")!)

    // 实例化音乐播放控件
    musicPlayer = try? AVAudioPlayer(contentsOfURL: musicUrl)

    // 准备(缓冲)播放
    musicPlayer.prepareToPlay()

    // 开始播放音乐
    musicPlayer.play()

2、本地音乐播放设置

  • Objective-C

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    // 设置代理,需遵守 <AVAudioPlayerDelegate> 协议
    musicPlayer.delegate = self;

    // 判断播放状态
    BOOL isPlaying = musicPlayer.isPlaying;

    // 获取音乐通道数
    NSUInteger numberOfChannels = musicPlayer.numberOfChannels;

    // 获取音乐时长
    /*
    获取音乐的长度,单位秒
    */
    NSTimeInterval duration = musicPlayer.duration;

    // 获取与输出设备相关联的当前播放进度
    NSTimeInterval deviceCurrentTime = musicPlayer.deviceCurrentTime;

    // 获取当前音乐文件的路径
    /*
    音乐文件播放控件由 url 创建,returns nil if object was not created with a URL
    */
    NSURL *currentMusicUrl = musicPlayer.url;

    // 获取当前音乐文件的数据
    /*
    音乐文件播放控件由 data 创建,returns nil if object was not created with a data object
    */
    NSData *currentMusicData = musicPlayer.data;

    // 设置声道
    /*
    -1.0:左声道, 0.0:左右声道(默认), 1.0:右声道
    */
    musicPlayer.pan = 1.0;

    // 设置音量
    /*
    音量范围是 0.0 ~ 1.0,默认为 1.0
    */
    musicPlayer.volume = 0;

    // 设置是否允许控制播发速度
    /*
    设置播放速度时必须设置此项为 YES,必须在 [musicPlayer prepareToPlay] 之前设置,默认为 NO
    */
    musicPlayer.enableRate = YES;

    // 设置播放速度
    /*
    enableRate 必须设置为 YES,1.0 is normal, 0.5 is half speed, 2.0 is double speed
    */
    musicPlayer.rate = 1;

    // 设置当前播放位置
    /*
    设置音乐从指定的时间处开始播放
    */
    musicPlayer.currentTime = 30;

    // 设置循环播放次数
    /*
    = 0:只播放一次(默认),> 0:播放设置的次数,< 0:循环播放
    */
    musicPlayer.numberOfLoops = 1;

    // 缓冲音乐
    [musicPlayer prepareToPlay];

    // 开始播放
    [musicPlayer play];

    // 定时播放
    /*
    在指定的时间播放音乐
    */
    [musicPlayer playAtTime:[[NSDate dateWithTimeIntervalSinceNow:10] timeIntervalSince1970]];

    // 暂停播放
    [musicPlayer pause];

    // 停止播放
    [musicPlayer stop];
  • Swift

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    // 设置代理
    /*
    需遵守 AVAudioPlayerDelegate 协议
    */
    musicPlayer.delegate = self

    // 判断播放状态
    let isPlaying: Bool = musicPlayer.playing

    // 获取音乐通道数
    let numberOfChannels: Int = musicPlayer.numberOfChannels

    // 获取音乐时长
    /*
    获取音乐的长度,单位秒
    */
    let duration: NSTimeInterval = musicPlayer.duration

    // 获取与输出设备相关联的当前播放进度
    let deviceCurrentTime: NSTimeInterval = musicPlayer.deviceCurrentTime

    // 获取当前音乐文件的路径
    /*
    音乐文件播放控件由 url 创建,returns nil if object was not created with a URL
    */
    let currentMusicUrl: NSURL = musicPlayer.url!

    // 获取当前音乐文件的数据
    /*
    音乐文件播放控件由 data 创建,returns nil if object was not created with a data object
    */
    let currentMusicData = musicPlayer.data

    // 设置声道
    /*
    -1.0:左声道, 0.0:左右声道(默认), 1.0:右声道
    */
    musicPlayer.pan = 1.0

    // 设置音量
    /*
    音量范围是 0.0 ~ 1.0,默认为 1.0
    */
    musicPlayer.volume = 0

    // 设置是否允许控制播发速度
    /*
    设置播放速度是必须设置此项为 YES,必须在 [musicPlayer prepareToPlay] 之前设置,默认为 NO
    */
    musicPlayer.enableRate = true

    // 设置播放速度
    /*
    enableRate 必须设置为 YES,1.0 is normal, 0.5 is half speed, 2.0 is double speed
    */
    musicPlayer.rate = 1

    // 设置当前播放位置
    /*
    设置音乐从指定的时间处开始播放
    */
    musicPlayer.currentTime = 30

    // 设置循环播放次数
    /*
    = 0:只播放一次(默认),> 0:播放设置的次数,< 0:循环播放
    */
    musicPlayer.numberOfLoops = 1

    // 缓冲音乐
    musicPlayer.prepareToPlay()

    // 开始播放
    musicPlayer.play()

    // 定时播放
    /*
    在指定的时间播放音乐
    */
    musicPlayer.playAtTime(NSDate(timeIntervalSinceNow: 10).timeIntervalSince1970)

    // 暂停播放
    musicPlayer.pause()

    // 停止播放
    musicPlayer.stop()

3、本地音乐文件解析

  • Objective-C

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    /*
    注意观察 commonKey 和 value:

    commonKey = title 歌曲名称
    commonKey = artist 歌手名称
    commonKey = albumName 专辑名称
    commonKey = artwork 专辑图片
    */
    NSString *titleString = nil;
    NSString *artistString = nil;
    NSString *albumNameString = nil;
    UIImage *artworkImage = nil;

    // 获取音乐文件路径
    NSURL *musicUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"蓝莲花" ofType:@"mp3"]];

    // 加载音乐文件
    AVURLAsset *URLAsset = [AVURLAsset URLAssetWithURL:musicUrl options:nil];

    // 解析音乐文件
    /*
    获取音乐文件中的信息,固定格式 org.id3
    */
    NSArray *musicInfoArray = [URLAsset metadataForFormat:@"org.id3"];

    for (AVMetadataItem *item in musicInfoArray) {

    // 解析歌曲名称
    if ([item.commonKey isEqualToString:@"title"]) {

    titleString = (NSString *)item.value;
    }

    // 解析歌手名称
    if ([item.commonKey isEqualToString:@"artist"]) {

    artistString = (NSString *)item.value;
    }

    // 解析专辑名称
    if ([item.commonKey isEqualToString:@"albumName"]) {

    albumNameString = (NSString *)item.value;
    }

    // 解析专辑图片
    if ([item.commonKey isEqualToString:@"artwork"]) {

    // value 值为 NSData 时,直接取值
    NSData *data = (NSData *)item.value;

    artworkImage = [UIImage imageWithData:data];
    }
    }

    // 显示解析值

    musicInfoLabel.text = [NSString stringWithFormat:@"歌曲名称: %@\n歌手名称: %@\n专辑名称: %@",
    titleString, artistString, albumNameString];

    musicInfoImageView.image = artworkImage;
  • Swift

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    /*
    注意观察 commonKey 和 value:

    commonKey = title 歌曲名称
    commonKey = artist 歌手名称
    commonKey = albumName 专辑名称
    commonKey = artwork 专辑图片
    */
    var titleString: String!
    var artistString: String!
    var albumNameString: String!
    var artworkImage: UIImage!

    // 获取音乐文件路径
    let musicUrl: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("蓝莲花", ofType: "mp3")!)

    // 加载音乐文件
    let URLAsset = AVURLAsset(URL: musicUrl, options: nil)

    // 解析音乐文件
    /*
    获取音乐文件中的信息,固定格式 org.id3
    */
    let musicInfoArray = URLAsset.metadataForFormat("org.id3")

    for item in musicInfoArray {

    let itemCommonKey: String? = (item as! AVMutableMetadataItem).commonKey

    // 解析歌曲名称
    if itemCommonKey == "title" {

    titleString = (item as! AVMutableMetadataItem).value as! String
    }

    // 解析歌手名称
    if itemCommonKey == "artist" {

    artistString = (item as! AVMutableMetadataItem).value as! String
    }

    // 解析专辑名称
    if itemCommonKey == "albumName" {

    albumNameString = (item as! AVMutableMetadataItem).value as! String
    }

    // 解析专辑图片
    if itemCommonKey == "artwork" {

    // value 值为 NSData 时,直接取值
    let data = (item as! AVMutableMetadataItem).value as! NSData

    artworkImage = UIImage(data: data)
    }
    }

    // 显示解析值

    musicInfoLabel.text = "歌曲名称: \(titleString)\n歌手名称: \(artistString)\n专辑名称: \(albumNameString)"

    musicInfoImageView.image = artworkImage

4、AVAudioPlayerDelegate 协议方法

  • Objective-C

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 播放完成
    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {

    }

    // 播放失败
    - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {

    }
  • Swift

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 播放完成
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {

    }

    // 播放失败
    func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer, error: NSError?) {

    }
文章目录
  1. 1. 前言
  2. 2. 1、本地音乐播放
  3. 3. 2、本地音乐播放设置
  4. 4. 3、本地音乐文件解析
  5. 5. 4、AVAudioPlayerDelegate 协议方法
隐藏目录