xcode 使用相同的按钮播放/暂停 [AVAudioPlayer]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6635604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Play/Pause with the same button [AVAudioPlayer]
提问by Aluminum
How can I play a sound with an IBAction
by pressing on a UIbutton
once and pause it by pressing the button again using AVAudioPlayer
? Also I want to change the state of that UIButton
when the sound is playing and when it's not.
如何IBAction
通过按UIbutton
一次并使用 再次按按钮暂停播放声音AVAudioPlayer
?我也想UIButton
在声音播放和不播放时改变它的状态。
Here's my code:
这是我的代码:
- (IBAction)Beat
{
if ([Media2 isPlaying])
{
[Media2 pause];
[Button17 setSelected:NO];
}
else
{
Path = [[NSBundle mainBundle] pathForResource:@"Beat" ofType:@"mp3"];
AVAudioPlayer *Media2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
[Media2 setDelegate:self];
[Media2 play];
[Button17 setSelected:YES];
}
}
回答by Splendid
Here's is simple method using BOOL
Variable.
这是使用BOOL
变量的简单方法。
Set playing = NO
in viewDidLoad
.
设置playing = NO
在viewDidLoad
.
-(void)PlayStop{
if (playing==NO) {
// Init audio with playback capability
[play setBackgroundImage:[UIImage imageNamed:@"hmpause.png"] forState:UIControlStateNormal];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:______ error:&err];
[audioPlayer prepareToPlay];
audioPlayer.delegate=self;
[audioPlayer play];
playing=YES;
}
else if(playing==YES){
[play setBackgroundImage:[UIImage imageNamed:@"Audioplay.png"] forState:UIControlStateNormal];
[audioPlayer pause];
playing=NO;
}
}
回答by Aluminum
Keep your audioPlayer instance ready to play using the below method.
使用以下方法让您的 audioPlayer 实例准备好播放。
/*
Prepares the audio file to play.
*/
-(void) initWithAudioPath:(NSString *) audioPath {
// Converts the sound's file path to an NSURL object
NSURL *audioPathURL = [[NSURL alloc] initFileURLWithPath:audioPath];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioPathURL error:nil];
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPathURL release];
}
-(void) pausePlaybackForPlayer:(AVAudioPlayer *) player {
[player pause];
}
-(void) startPlaybackForPlayer:(AVAudioPlayer *) player {
if (![player play]) {
NSLog(@"Could not play %@\n", player.url);
}
}
- (IBAction)Beat {
if (audioPlayer.playing == NO) {
// Audio player is not playing.
// Set the button title here to "stop"...
[self startPlaybackForPlayer:audioPlayer];
}else {
// Audio player is playing.
// Set the button title here to "play"...
[self pausePlaybackForPlayer:audioPlayer];
}
}