iOS 播放自定义或者系统声音文件
2016-03-26 本文已影响1168人
九月文化
Objective-C
#import <Foundation/Foundation.h>
@interface OTSAudioPlayer : NSObject
/**
* 播放自定义或者系统声音文件
*
* @param aFileName 要播放的文件名
* @param aBundelName 存储路径
* @param ext 文件后缀
* @param alert 是否播放自定义或者系统文件
*
* @return UIColor
*/
+ (void)playSoundWithFileName:(NSString *)aFileName
bundleName:(NSString *)aBundelName
ofType:(NSString *)ext
andAlert:(BOOL)alert;
@end
#import "OTSAudioPlayer.h"
#import <AudioToolbox/AudioToolbox.h>
#import "OTSLog.h"
@implementation OTSAudioPlayer
+ (void)playSoundWithFileName:(NSString *)aFileName bundleName:(NSString *)aBundleName ofType:(NSString *)ext andAlert:(BOOL)alert
{
// 文件存储路径
NSBundle *bundle = [NSBundle mainBundle];
if (aBundleName.length) {
bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:aBundleName withExtension:@"bundle"]];
}
if (!bundle) {
OTSLogE(@"play sound cannot find bundle: [%@]", aBundleName);
return;
}
// 文件路径
NSString *path = [bundle pathForResource:aFileName ofType:ext];
if (!path) {
OTSLogE(@"paly sound cannot find file [%@] in bundle [%@]", aFileName , aBundleName);
return;
}
NSURL *urlFile = [NSURL fileURLWithPath:path];
// 声明需要播放的音频文件ID[unsigned long];
SystemSoundID ID;
// 创建系统声音,同时返回一个ID
OSStatus err = AudioServicesCreateSystemSoundID((__bridge CFURLRef)urlFile, &ID);
if (err != kAudioServicesNoError) {
OTSLogE(@"play sound cannot create file url [%@]", urlFile);
return;
}
// 根据ID播放自定义系统声音
if (alert) {
AudioServicesPlayAlertSound(ID);
} else {
AudioServicesPlaySystemSound(ID);
}
}
@end
Swift
import UIKit
import AudioToolbox
class OTSAudioPlayer: NSObject {
/**
* 播放自定义或者系统声音文件
*
* @param aFileName 要播放的文件名
* @param aBundelName 存储路径
* @param ext 文件后缀
* @param alert 是否播放自定义或者系统文件
*
* @return UIColor
*/
class func playSoundWithFileName(aFileName : String?, aBundleName : String?, ext : String?, alert : Bool) -> Void
{
// 文件存储路径
var bundle : NSBundle?
if (aBundleName! as NSString).length > 0 {
let url: NSURL? = NSBundle.mainBundle().URLForResource(aBundleName, withExtension: "bundle")
bundle = NSBundle.init(URL: url!)
}
if bundle == nil {
print("play sound cannot find bundle: [\(aBundleName)]")
return
}
// 文件路径
let path = bundle!.pathForResource(aFileName, ofType: ext)
if path == nil {
print("paly sound cannot find file [\(aFileName)] in bundle [\(aBundleName)]")
return
}
let urlFile = NSURL.fileURLWithPath(path!)
// 声明需要播放的音频文件ID[unsigned long];
var ID : SystemSoundID = 0 // 强制初始化
// 创建系统声音,同时返回一个ID
let err = AudioServicesCreateSystemSoundID(urlFile, &ID)
if err != kAudioServicesNoError {
print("play sound cannot create file url [\(urlFile)]");
return;
}
// 根据ID播放自定义系统声音
if (alert) {
AudioServicesPlayAlertSound(ID);
} else {
AudioServicesPlaySystemSound(ID);
}
}
}