• iOS 设置铃声---加载音乐和音频然后进行播放


    在有些应用中需要用到背景音乐和音效,那在程序中是这么实现的。

    1.首先加载背景音乐需要用到AVFoundation框架

    2.音乐资源都是在包里的,所以需要获得包路径,涉及方法- (id)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;

    url其实就是包地址,可以通过[[NSBundlemainBundle]pathForResource:@"背景音乐" ofType:@"caf"];获得到路径path,然后用NSURL的fileURLWithPath方法将path转化为url;

    3.设置音乐播放次数.numberOfLoops。设为0仅播放一次;设为1则循环1次播放2次;设为-1则循环播放不间断;

    4.设置音乐声音大小.volume。

    5.准备播放,调用方法 prepareToPlay。

    6.开始播放,调用方法 play;停止播放:stop;

    1 NSString *path = [[NSBundle mainBundle]pathForResource:@"背景音乐" ofType:@"caf"];
    2 NSURL *url = [NSURL fileURLWithPath:path];
    3 AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    4 player.numberOfLoops = -1;
    5 player.volume = 0.5f;
    6 [player prepareToPlay];
    7 [player play];

    而加载音效则需要用到AudioToolbox框架,和音乐一样需要加载包路径,使用的方法是AudioServicesCreateSystemSoundID,这是个c语言的方法,其中传入的url需要用到__bridge进行转换,传出一个SystemSoundID来提供播放的时候调用,播放使用的方法是AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID) 。

    1 NSString *path = [[NSBundle mainBundle]pathForResource:soundFileName ofType:nil];
    2 NSURL *url = [NSURL fileURLWithPath:path];
    3 SystemSoundID soundID;
    4 AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
    5  
    6 AudioServicesPlaySystemSound(soundID);<br>

    此外还有个方法是AudioServicesPlayAlertSound,此方法在播放音效的同时会发出震动,给用户提醒。

  • 相关阅读:
    Canvas 3D球形文字云动画特效
    CSS3实现各种表情
    使用html+css+js实现弹球游戏
    CSS3实现图片木桶布局
    JQ实现弹幕效果
    css实现导航切换
    使用JS实现俄罗斯方块游戏
    JS实现文本中查找并替换字符
    Qt笔记之 01主函数和配置文件详解
    C++学习笔记之 异常
  • 原文地址:https://www.cnblogs.com/Wild-orangutans/p/4501181.html
Copyright © 2020-2023  润新知