zoukankan      html  css  js  c++  java
  • iOS Dev (21) 用 AVPlayer 播放一个本地音频文件

     

    iOS Dev (21) 用 AVPlayer 播放一个本地音频文件

    前言

    这篇文章与上一篇极其相似,要注意别看错。

    步骤

    • 第一步:在 Project - TARGETS - Project名 - Build Phases - Link Binary With Libraries,添加 AVFoundation.framework。
    • 第二步:创建一个 UIViewController 的子类 PlayerViewController。
    • 第三步:在 PlayerViewController 中添加一个属性 AVPlayer。
    • 第四步:在 PlayerViewController 的 viewDidLoad 方法中实现最主要的代码。

    关键代码

    .h

    #import <UIKit/UIKit.h>
    #import <AVFoundation/AVFoundation.h>
    
    @interface PlayViewController: UIViewController
    
    @property (strong, nonatomic) AVPlayer *player;
    
    @end
    

    .m

    #import "PlayerViewController.h"
    
    @interface PlayerViewController ()
    
    @end
    
    @implementation PlayerViewController
    
    - (void) viewDidLoad
    {
        [super viewDidLoad];
    
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        [audioSession setActive:YES error:nil];
    
        NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"rem" ofType:@"wav"];
        NSURl *audioUrl = [NSURL fileURLWithPath:audioPath];
        NSError *playerError;
        _player = [[AVPlayer alloc] initWithContentsOfURL:audioUrl error:&playerError];
        if (_player === NULL)
        {
            NSLog(@"fail to play audio :(");
            return;
        }
    
        [_player setVolume:1];
        [_player play];
    }
    
    - (void) didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
    }
    
    @end
    

    几个重要的点:

    • 必须要用 AVAudioSession,否则木有声音啊。
    • 不要把 AVPlayer 当做局部变量(具体说在这个例子中,不要在 viewDidLoad 中定义)。
    • 要找好路径,这里用 mainBundle,不要搞错。

    源码

    http://download.csdn.net/detail/prevention/6817053

    -

    转载请注明来自:http://blog.csdn.net/prevention

  • 相关阅读:
    GIT基本概念和用法总结
    SELECT联动
    PHP无级分类续及搜索功能,分组分页
    PHP管理员登陆、验证与添加(前端验证)
    PHP手写cms 缓存Cache
    将本地文件上传到Ftp上的一些操作【转】
    SQL对时间的处理
    SQL Server游标的使用【转】
    修改数据表字段长度
    Web.Config加密【转】
  • 原文地址:https://www.cnblogs.com/riasky/p/3509130.html
Copyright © 2011-2022 走看看