Joh*_*ker 36 iphone audio caching nsdata avaudioplayer
我试图通过iPhone上的AVAudioPlayer播放(非常短 - 少于2秒)的音频文件来消除启动延迟.
一,代码:
NSString *audioFile = [NSString stringWithFormat:@"%@/%@.caf", [[NSBundle mainBundle] resourcePath], @"audiofile"];
NSData *audioData = [NSData dataWithContentsOfMappedFile:audioFile];
NSError *err;
AVAudioPlayer *audioPlayer = [(AVAudioPlayer*)[AVAudioPlayer alloc] initWithData:audioData error:&err];
audioPlayer.delegate = self;
[audioPlayer play];
Run Code Online (Sandbox Code Playgroud)
一旦完成,我还实现了audioPlayerDidFinishPlaying方法来释放AVAudioPlayer.
我第一次播放音频时滞后是显而易见的 - 至少2秒.然而,之后立即播放声音.我怀疑那个罪魁祸首是[NSData dataWithContentsOfMappedFile]最初从闪存中读取了很长时间,但后来读取速度很快.不过,我不确定如何测试.
是这样的吗?如果是这样,我是否应该预先缓存NSData对象并积极地在低内存条件下清除它们?
Joh*_*ker 37
延迟似乎与第一次实例化AVAudioPlayer有关.如果我加载任何音频,运行[audioPlayer prepareToPlay]然后立即释放它,我所有其他音频的加载时间非常接近不可察觉.所以现在我在applicationDidFinishLaunching中这样做,其他一切运行良好.
我在文档中找不到任何相关内容,但看起来确实如此.
Tay*_*ier 11
这是我所做的(在一个单独的线程中):
[audioplayer start]
[audioplayer stop]
self.audioplayer = audioplayer
Run Code Online (Sandbox Code Playgroud)
[audioplayer prepareToPlay]似乎是一个异步方法,因此如果音频实际上已准备就绪,您无法确定它何时返回.
在我的情况下,我打电话开始实际开始播放 - 这似乎是同步的.然后我立即停止它.无论如何,在模拟器中,我听不到此活动发出的任何声音.现在声音"真的"准备播放了,我将局部变量分配给成员变量,因此线程外部的代码可以访问它.
我必须说我觉得有点令人惊讶的是,即使在iOS 4上加载一个长度仅为4秒的音频文件也只需要2秒钟....
如果您的音频长度小于30秒且采用线性PCM或IMA4格式,并打包为.caf,.wav或.aiff,则可以使用系统声音:
导入AudioToolbox框架
在.h文件中创建此变量:
SystemSoundID mySound;
Run Code Online (Sandbox Code Playgroud)
在.m文件中,在init方法中实现它:
-(id)init{
if (self) {
//Get path of VICTORY.WAV <-- the sound file in your bundle
NSString* soundPath = [[NSBundle mainBundle] pathForResource:@"VICTORY" ofType:@"WAV"];
//If the file is in the bundle
if (soundPath) {
//Create a file URL with this path
NSURL* soundURL = [NSURL fileURLWithPath:soundPath];
//Register sound file located at that URL as a system sound
OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)soundURL, &mySound);
if (err != kAudioServicesNoError) {
NSLog(@"Could not load %@, error code: %ld", soundURL, err);
}
}
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
在您的IBAction方法中,您可以使用以下方法调用声音:
AudioServicesPlaySystemSound(mySound);
Run Code Online (Sandbox Code Playgroud)
这对我有用,播放按下按钮时非常接近的声音.希望这对你有所帮助.
我采取了一种适合我的替代方法。我在其他地方看到过这种技术(尽管我现在不记得那是在哪里)。
简而言之,在执行任何其他操作之前,通过加载并播放简短的“空白”声音来对声音系统进行预检。viewDidLoad
对于我在视图控制器的方法中预加载的持续时间为 0.1 秒的短 mp3 文件,代码如下所示:
NSError* error = nil;
NSString* soundfilePath = [[NSBundle mainBundle] pathForResource:@"point1sec" ofType:@"mp3"];
NSURL* soundfileURL = [NSURL fileURLWithPath:soundfilePath];
AVAudioPlayer* player = [[[AVAudioPlayer alloc] initWithContentsOfURL:soundfileURL error:&error] autorelease];
[player play];
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您可以创建自己的空白 mp3,或者在 google 上搜索“空白 mp3”以查找并下载其他人已经构建的空白 mp3。
归档时间: |
|
查看次数: |
21320 次 |
最近记录: |