2016-08-09 131 views
0

我使用AVPlayer。它延遲播放音頻。我想播放聲音,然後點擊UIButton(音頻),我想播放視頻。我怎樣才能做到這一點?誰能幫我?如何播放音頻沒有任何延遲使用AVPlayer

-(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)]; 

} 
+0

你想要什麼播放音頻或視頻?並添加您的代碼問題,你已經嘗試過! – Lion

+0

請顯示你的努力,並添加一些你嘗試過的代碼。 –

+0

你的代碼播放按鈕點擊音頻看起來不錯,不會延遲。如果你得到延遲,你有沒有檢查音頻文件沒有初始的靜音間隙?如果沒有,那麼其他東西可能會阻止主線程,你需要檢查 –

回答

2

創建新類

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

在相對的ViewController加載聲音

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

玩要玩

testSound.play() 
+0

要添加更多信息:關鍵是在應用(或視圖)初始化時創建AVAudioPlayer一次,然後每次需要時只調用.play()。 –