gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:23:46 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com