播放音乐

作品链接:
http://www.jianshu.com/users/1e0f5e6f73f6/top_articles

1.导入框架

#import <AVFoundation/AVFoundation.h>

2.初始化字典

static NSMutableDictionary *_players;
+ (void)initialize
{
    _players = [NSMutableDictionary dictionary];
}

3.点击事件的处理

// 开始播放
- (IBAction)start {
    [PHAudioTool playMusicWithSoundName:@"播放文件名称"];
}
//暂停播放
- (IBAction)pause {
    [PHAudioTool pauseMusicWithSoundName:@"播放文件名称"];
}
//停止播放
- (IBAction)stop {
    [PHAudioTool stopMusicWithSoundName:@"播放文件名称"];
}

4.播放音乐

+ (void)playMusicWithSoundName:(NSString *)fileName
{
    // 1.创建空播放器
    AVAudioPlayer *player = nil;
    // 2.从字典中取出播放器
    player = _players[fileName];
    // 3.判断字典是否为空
    if (player == nil) {
        // 4.生成对应的音乐文件
        NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
        // 5.创建对应的播放器
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
        // 6.保存到字典中
        [_players setObject:player forKey:fileName];
        // 7.准备播放
        [player prepareToPlay];
    }
    // 8.开始播放
    [player play];
}

5.暂停音乐

+ (void)pauseMusicWithSoundName:(NSString *)fileName
{
    // 1.从字典中取出播放器
    AVAudioPlayer *player = _players[fileName];
    // 2.暂停音乐
    if (player) {
        [player pause];
    }
}

6.停止音乐

+ (void)stopMusicWithSoundName:(NSString *)fileName
{
    // 1.从字典中取出播放器
    AVAudioPlayer *player = _players[fileName];
    // 2.停止音乐
    if (player) {
        [player stop];
        [_players removeObjectForKey:fileName];
        player = nil;
    }
```
 注意:AVAudioPlayer播放值适用于本地文件
 ```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 简单音效处理 导入"AVFoundation"框架 创建URL地址 系统音效文件 SystemSoundID = ...
    e85a0a8a9ba4阅读 353评论 0 1
  • iOS 4开始引入的multitask,我们可以实现像ipod程序那样在后台播放音频了。如果音频操作是用苹果官方的...
    _烈日阅读 7,932评论 0 1
  • 一、播放音乐。 1.首先导入AVFoundation.framework 2.开始在当前控制器的.m文件里 #im...
    小专注阅读 348评论 0 0
  • 上月去北京学习了《中国式众筹》。 杨众筹经常说起,建议各行各业各地区垂直领域里面众筹一个咖啡馆和一本杂志。 当时觉...
    艾小农阅读 246评论 0 0
  • 我期待着繁花似锦的午后 奈何繁花 疏落 我又期待着日暮西斜的黄昏 黄昏终于 如期而至 我想起了某个久远的故人 想起...
    夜的暮阅读 337评论 0 0