使用AVAudioPlayer帮助停止音频 [英] Help stopping audio using AVAudioPlayer

查看:150
本文介绍了使用AVAudioPlayer帮助停止音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧我有两个问题。我正在使用AVAudioPlayer播放.caf格式的简单音频文件。我要做的是有一个播放和暂停按钮。以下是从按钮播放音频的简单IBAction示例。

Alright I have two problems. I'm using AVAudioPlayer to play a simple audio file in .caf format. What I'm trying to do is have a play and pause button. Here is a sample of a simple IBAction to play the audio from a button.

- (IBAction) clear {
NSString *path = [[NSBundle mainBundle] pathForResource:@"clear" ofType:@"caf"];
AVAudioPlayer* myAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
myAudio.delegate = self;
myAudio.volume = 1.0;
myAudio.numberOfLoops = 0;
[myAudio play]; 
}

因此,当我继续使用该方法创建另一个IBAction时...... / p>

So when I go ahead and create another IBAction with the method...

- (IBAction) stopaudio {
[myAudio stop];
audioPlayer.currentTime = 0;
}

我编译并且xcode告诉我,stopaudio IBAction中的myAudio未定义。我如何修复它以便能够在另一个IBAction中访问myAudio?

I compile and xcode tells me that myAudio in the stopaudio IBAction is not defined. How do I fix it so I'm able to access myAudio in another IBAction?

我的第二个问题是我正在使用NavigationController来设置TableView,当我制作时一个选择它带我到UIView有一个后退按钮回到TableView。我要做的是当我回到TableView时杀死我在UIView中播放的任何音频。上面的代码是我将在UIView中拥有的代码的一部分。

My Second question is that I'm using NavigationController to setup a TableView, when I make a selection it takes me to a UIView with a back button to go back to the TableView. What I'm trying to do is to kill any audio that I have playing in the UIView when I go back to the TableView. The code above is part of the code that I'm going to have in the UIView.

这也是一个简单的问题。假设我有一个1分钟的音频文件。再次单击播放将在旧实例播放完毕之前重叠该音频的新实例。如何检查myAudio是否正在播放并且在myAudio播放完毕之前不允许再次播放?

Also one quick question. Lets say I have an audio file that is 1 minute long. Clicking play again will overlap a new instance of that audio before the old instance is done playing. How can I check to see if myAudio is playing and not allow it to be played again until myAudio is finished playing?

谢谢!

推荐答案

首先,您应该阅读文档。它将删除几乎所有的问题。不过,要从类的所有方法访问您的AVAudioPlayer实例,您应该在.h文件中定义它。要停止播放器返回上一个屏幕,请在 viewWillDisappear中调用 [myAudio stop] :( BOOL)动画方法。关于你的上一个问题。如果在.h文件中定义 myAudio ,您将能够检查它是否正在播放。 smth like

First of all, you should read the documentation. It will remove almost all of your questions. Nevertheless, to have access to your instance of AVAudioPlayer from all methods of your class, you should define it in your .h file. To stop your player on returning to the previous screen, call [myAudio stop] in your viewWillDisappear:(BOOL)animated method. About your last question. If you define myAudio in your .h file, you will be able to check if it is playing now. smth like


- (IBAction) clear {
    if(![myAudio isPlaying]){
        [myAudio play]; 
    }

}

这篇关于使用AVAudioPlayer帮助停止音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆