在播放动态音频之前创建AVAudioPlayer对象

时间:2013-08-02 11:45:08

标签: ios

每当我播放如下的音频文件时,开始播放音频只需几秒钟。我从一些论坛上看到并了解到,如果我们在那里分配对象,AVAudioPlayer将需要几秒钟才能开始播放。我想更早地分配这个对象(可能是Appdelegate本身),之前我想玩,所以当我想玩它时,它会立即播放。

NSURL *audioPathURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:audioName ofType:@"wav"]];

audioP = [[AVAudioPlayer alloc]initWithContentsOfURL:audioPathURL error:NULL];
[appDelegate.audioP play];

但是,我在运行时动态传递音频网址,所以我想知道如何更早地分配对象,然后能够在以后传递动态音频网址路径?

请注意,我的问题与此问题不同Slow start for AVAudioPlayer the first time a sound is played 在现有问题中,他们讲述了一个音频文件并在需要时播放。但是,我有许多不同的音频文件和url路径随机生成并在运行时播放,所以我不知道设置和播放的实际url路径是什么。那么,这里提到的答案 - > Slow start for AVAudioPlayer the first time a sound is played 对我的问题没有帮助。 我不能使用prepareToPlay,因为音频路径url是在运行时设置的,并且不是只有一个音频被用于所有时间播放,将有超过20个音频文件随机选择并设置为一次播放一个。所以,我需要正确的答案,这不是一个重复的问题。

谢谢!

2 个答案:

答案 0 :(得分:0)

对于单个文件,解决方案:

file.h

#import <AVFoundation/AVFoundation.h>

@interface AudioPlayer : UIViewController <AVAudioPlayerDelegate> {


}

要使用按钮,请在- (IBAction)Sound:(id)sender;

中添加file.h

现在在file.m

//这是一个动作,但您可以在void内部使用来启动自动

@implementation AudioPlayer {

    SystemSoundID soundID;
}

- (IBAction)Sound:(id)sender {

    AudioServicesDisposeSystemSoundID(soundID);
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;

//you can use here extension .mp3 / .wav / .aif / .ogg / .caf / and more

    soundFileURLRef =  CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"sound" ,CFSTR ("mp3") , NULL);
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);

}

如果您想使用代码从URL播放音频,可以使用:

#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface AudioPlayer : UIViewController <AVAudioPlayerDelegate> {

AVPlayer *mySound;

}

@property (strong, nonatomic) AVPlayer *mySound;
@end

file.m

- (IBAction)playPause:(id)sender {

 if (mySound.rate == 0){

    NSURL *url = [NSURL URLWithString:@"http://link.mp3"];
    mySound = [[AVPlayer alloc] initWithURL:url];
    [mySound setAllowsExternalPlayback:YES];
    [mySound setUsesExternalPlaybackWhileExternalScreenIsActive: YES];
    [mySound play];

} else {

[mySound pause];

}

}

希望这可以帮到你!

答案 1 :(得分:0)

减少第一次加载+播放的延迟可以做的一件事是在你需要之前通过加载和播放一个虚拟文件来“旋转”基础音频系统。例如,在application:didFinishLaunchingWithOptions:中添加一些代码:

// this won't effect the problem you're seeing, but it's good practice to explicitly
// set your app's audio session category
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
NSURL *audioURL = [[NSBundle mainBundle] URLForResource:@"dummy.wav" withExtension:nil];
AVAudioPlayer *dplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
// we don't want to hear it (alternatively, the audiofile you use for this purpose can be silence.)
dplayer.volume = 0.f;
[dplayer prepareToPlay];
[dplayer play];
[dplayer stop];

一旦此代码完成,AVAudioPlayer实例的后续实例化和回放应具有相当低的延迟(当然远低于1秒)