zoukankan      html  css  js  c++  java
  • 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);

  • 相关阅读:
    [Codeforces967C]Stairs and Elevators(二分查找)
    [Codeforces976E]Well played!(贪心)
    [USACO12JAN]视频游戏的连击Video Game Combos(AC自动机+DP)
    [HDU2222]Keywords Search(AC自动机)
    [BZOJ1030][JSOI2007]文本生成器(AC自动机+DP)
    基于ZooKeeper实现——分布式锁与实现
    基于Redis实现——分布式锁与实现
    java 接口请求返回通用json
    Java SHAA加密
    (转)一些牛人榜样,多看看他们写的东西(后续整理牛人的blog等)
  • 原文地址:https://www.cnblogs.com/suenihy/p/3520692.html
Copyright © 2011-2022 走看看