• iOS 播放声音文件


    播放声音可以通过3中方式来完成。

    1.AVAudioPlayer

    使用简单方便,但只能播放本地音频,不支持流媒体播放。

      //初始化文件地址

    NSBundle *bundle = [NSBundle mainBundle];

    NSString *filePath = [bundle pathForResource:@"fileName" ofType:@"mp3"];

    NSURL *url = [NSURL fileURLWithPath:filePath];

      

    //初始化音频对象

    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];

    [player prepareToPlay];

    //播放

    if([player play])

    {

    NSLog(@"正在播放");

    }

      

    if([player isPlaying])

    {

    NSLog(@"检测播放状态");

    }

      

    //暂停播放

    [player pause];

      

    //停止播放

    [player stop];

      

    //其他常用属性

    //1.音量

    player.volume = 0.8;//设置音量(0-1之间)

      

    //2.循环次数

    player.numberOfLoops = 3;//默认只播放一次

    NSLog(@"总时长 %f",player.duration); //总时长

      

    //3.播放位置

    player.currentTime = 15.0;//从指定的位置开始播放

    这里可以通过添加代理来监听文件是否播放成功或其他的方法

    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

    {

    NSLog(@"音频文件播放完成");

    }


    2.AVPlayer

    iOS4.0以后,可以使用AVPlayer播放本地音频和支持流媒体播放,但提供接口较少,处理音频不够灵活。

      //可以播放网络资源

    NSString *filePath = @"http://www.xxx.1112321.mp3";

    NSURL *url = [NSURL URLWithString:filePath];

      

    AVPlayer *player = [[AVPlayer alloc] initWithURL:url];

    [player play];

    3.播放系统声音

      //1.注册系统声音

    SystemSoundID soundID;

    AudioServicesCreateSystemSoundID((CFURLRef)@"filePathUrl", &soundID);

    //filePathUrl文件的类型格式为:caf/wav/aiff格式,且时长小于30s

      

    //2.1播放声音

    AudioServicesPlaySystemSound(soundID);

      

    //2.2播放震动

    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

  • 相关阅读:
    Sql Server 2005开发新特性笔记
    动态调用Web Service(ZT)
    web.config详解(配置文件节点说明)
    SQL分页语句
    在SQL Server 2005数据库中更改数据架构
    [转]在WinForm应用程序中实现自动升级
    DataGrid 导出 EXCEL(简单,实用)
    在WinForm中使用WebServices来实现软件自动升级(AutoUpdate)(C#)
    工作小结TextBox为密码框赋值技巧,CSS溢出显示省略号方法
    自动更新程序源码下载(C#.Net)
  • 原文地址:https://www.cnblogs.com/suenihy/p/3520692.html
Copyright © 2020-2023  润新知