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);

  • 相关阅读:
    Java SE入门(十三)——高级API
    Java SE入门(十二)——修饰符与内部类
    Java SE入门(十一)——接口与多态
    数据结构与算法(一)——绪论
    break与continue的区别以及终止函数的return false
    文字超出隐藏显示省略号及鼠标放上去显示全部文字信息的写法
    组件有新增修改两种状态该怎么使用
    Math常用的属性和方法
    模块化开发及import用法
    element时间日期选择器组件设置默认时间
  • 原文地址:https://www.cnblogs.com/suenihy/p/3520692.html
Copyright © 2011-2022 走看看