【问题标题】:How to Play audios without any delay using AVPlayer如何使用 AVPlayer 毫无延迟地播放音频
【发布时间】:2016-08-09 12:40:54
【问题描述】:

我正在使用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)];

 }

【问题讨论】:

  • 你想播放什么音频或视频?并添加您尝试过的有问题的代码!
  • 请展示您的努力并添加一些您尝试过的代码。
  • 您在单击按钮时播放音频的代码看起来不错,并且不会增加延迟。如果您遇到延迟,您是否检查过音频文件上没有初始静音间隙?如果没有,那么可能是其他东西阻碍了主线程,您需要检查
  • 一切正常。但是,在 audioPlayerDidFinishPlaying 中重定向到 mainView 后,音频未按预期播放。稍等片刻后播放

标签: ios objective-c avplayer avplayerviewcontroller


【解决方案1】:

新建类

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()
}
}

在相对视图控制器中加载声音

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

在你想玩的地方玩

testSound.play()

【讨论】:

  • 添加更多信息:关键是在应用(或视图)初始化时创建一次 AVAudioPlayer,然后每次需要时只调用 .play()。
猜你喜欢
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
相关资源
最近更新 更多