ios - 如何使用 AVPlayer 无延迟地播放音频

标签 ios objective-c avplayer avplayerviewcontroller

我正在使用 AVPlayer。它会在延迟一段时间后播放音频。我想在点击 UIButton 之后播放声音(音频),我想播放视频。我怎样才能做到这一点?谁能帮帮我?

-(IBAction) someMethod3:(id) sender {
 [self Playaudio];
 }

-(voidPlayaudio {

 NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"tap" ofType: @"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
NSError *error;
musicplayer =  [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
musicplayer.delegate = self;
[musicplayer prepareToPlay];
[musicplayer play];
}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{

[self playVideo:indexvalue];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mainView:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

}

-(void) playVideo:(int)index {

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:[_videos objectAtIndex:index] ofType: nil];
url = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVPlayerItem *currentItem = [AVPlayerItem playerItemWithURL:url];
playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.videoGravity = AVLayerVideoGravityResize;
playerViewController.view.frame = self.view.bounds;
playerViewController.showsPlaybackControls = NO;
video = [AVPlayer playerWithPlayerItem:currentItem];
playerViewController.player = _video;
playerViewController.view.userInteractionEnabled = false;
[playerViewController.player play];
self.view.autoresizesSubviews = YES;

[self.view addSubview:playerViewController.view];
}

-(void)Mainview:(NSNotification*)notification {
UIButton * Button = [[UIButton alloc] initWithFrame: CGRectMake(10, 50, 30,20)];

 }

最佳答案

创建新类

import AVFoundation

class Sound {

var audioPlayer = AVAudioPlayer()

init(name: String, type: String) {
    let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(name, ofType: type)!)
    do {
        audioPlayer = try AVAudioPlayer(contentsOfURL: coinSound)
        audioPlayer.prepareToPlay()
    } catch let error as NSError {
        print(error.description)
    }
}

func play() {
    audioPlayer.play()
}

func stop() {
    audioPlayer.stop()
}
}

在相对 View Controller 中加载声音

 let testSound = Sound(name: "alarm", type: "caf")

在你想玩的地方玩

testSound.play()

关于ios - 如何使用 AVPlayer 无延迟地播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38851046/

相关文章:

ios - 在 Swift 2 中按下 UINavigation Controller 上的 'back' 按钮时让 AVPlayer 继续播放

ios - 播放完成后如何自动关闭 AVPlayer?

ios - 以编程方式在其他 View 的底部添加 subview

ios - 我怎样才能找到给定日期的格林威治标准时间

iphone - 为所有 navigationcontroller 和 navigationitem 设置 titleview

iphone - 如何实现initWithObjects?

ios - 在 IOS 8 中使用自动布局调整单元格大小

iOS使视频背景模糊

ios - 看不到 "Hold for Developer Release"选项

ios - 从非 UIViewController 类在 UIViewController 上设置标签文本