iOS音頻播放(系統(tǒng)音效播放)

昨天遇到了系統(tǒng)提示音的播放(類似于系統(tǒng)短音提示音,按鍵提示音),最終發(fā)現(xiàn)其實(shí)系統(tǒng)聲音的播放其實(shí)很簡(jiǎn)單,在這里做一個(gè)紀(jì)錄
這里的聲音播放使用AVFoundation框架

播放系統(tǒng)音效(系統(tǒng)提示音效)

//其中的soundID是系統(tǒng)音效ID可以在下面地址找到
//soundID的類型是SystemSoundID其實(shí)就是UInt32需要強(qiáng)轉(zhuǎn)一下eg:(UInt32)1007
AudioServicesPlaySystemSound(soundID);

系統(tǒng)音效ID查看:http://iphonedevwiki.net/index.php/AudioServices

播放網(wǎng)絡(luò)緩存到沙盒document下的音頻文件

//name是音頻文件的名稱
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *urlString = [documents stringByAppendingPathComponent:name];

SystemSoundID soundID = 0;

if (!soundIDs)
{
    soundIDs = [NSMutableDictionary dictionary];
}
else
{
    soundID = (SystemSoundID)[soundIDs[soundIDName] integerValue];
}

if (soundID == 0)
{
    NSURL *url = [NSURL URLWithString:urlString];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)url, &soundID);
    soundIDs[soundIDName] = [NSString stringWithFormat:@"%zd",soundID];
}
AudioServicesPlaySystemSound(soundID);

播放網(wǎng)絡(luò)app的boundle中的音頻文件

//name是音頻文件的名稱
NSString *urlString = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] pathForResource:name ofType:nil]];

SystemSoundID soundID = 0;

if (!soundIDs)
{
    soundIDs = [NSMutableDictionary dictionary];
}
else
{
    soundID = (SystemSoundID)[soundIDs[soundIDName] integerValue];
}

if (soundID == 0)
{
    NSURL *url = [NSURL URLWithString:urlString];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)url, &soundID);
    soundIDs[soundIDName] = [NSString stringWithFormat:@"%zd",soundID];
}
AudioServicesPlaySystemSound(soundID);

為了方便使用將音頻播放做了下簡(jiǎn)單封裝成JLBAudioTool使用簡(jiǎn)單,有興趣可以看一下https://github.com/tiancanfei/JLBAudioTool

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容