我目前正在制作一个实时流音乐应用程序,并且我已经使用了所有按钮并可以从中播放声音。
但是,如果正在播放一种声音,则当我按下另一个按钮时,它只会播放原始声音,而不是停止播放原始声音,请帮助我如何解决此问题?
非常感谢
- (IBAction)Play1:(id)sender {
NSString *stream = @".mp3"
;
NSURL *url = [NSURL URLWithString:stream];
NSURLRequest *urlrequest = [NSURLRequest requestWithURL: url];
[Webview1 loadRequest:urlrequest];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer play];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
实施此行为取决于您。我建议您跟踪可能正在播放的任何AVAudioPlayer,并在创建和启动新的AVAudioPlayer之前将其停止。
例如,您可以使用属性来存储您创建的每个AVAudioPlayer。然后,在创建新的之前,请停止旧的。
有很多方法可以做到这一点。假设每个按钮都有一个URL,这是一个可能的过程:
// note that audioPlayer is a property. It might be defined like this:
// @property (nonatomic,strong) AVAudioPlayer *audioPlayer
- (IBAction)button1Pressed:(id)sender {
NSString *stream = @"url1.mp3";
[self playUrl:[NSURL URLWithString:stream]];
}
- (IBAction)button2Pressed:(id)sender {
NSString *stream = @"url2.mp3";
[self playUrl:[NSURL URLWithString:stream]];
}
- (void) playUrl:(NSURL *) url {
//stop a previously running audioPlayer if it is running:
[audioPlayer pause]; //this will do nothing if audioPlayer is nil
//create a new one and start it:
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[audioPlayer start];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句