ios - AVAudioPlayer 在播放时不会停止
<p><p>我正在开发一款通过逐句播放声音文件来播放旁白的应用。
使用下面的代码,它按预期播放。但是,添加“停止”按钮停止播放后,我发现“停止”按钮并没有停止声音。</p>
<p>我在按下“播放”按钮之前测试了“停止”按钮,没有问题(消息已打印)。但是,在按下“播放”后,当 NarrationPlayer 正在播放时,“停止”按钮不起作用(没有打印任何消息)。</p>
<p>知道有什么问题吗?</p>
<pre><code>import UIKit
import AVFoundation
class ViewController: UIViewController,AVAudioPlayerDelegate {
var NarrationPlayer:AVAudioPlayer = AVAudioPlayer()
var soundlist: = []
var counter = 0
}
func playSound(_ soundfile: String) {
let NarPath = Bundle.main.path(forResource: soundfile, ofType:"mp3")!
let NarUrl = URL(fileURLWithPath: NarPath)
do {
NarrationPlayer = try AVAudioPlayer(contentsOf: NarUrl)
NarrationPlayer.delegate = self
} catch{
print(error)
}
NarrationPlayer.play()
}
@IBAction func play(_ sender: Any) {
soundlist.append("a")
soundlist.append("b")
soundlist.append("c")
playSound("first")
while counter < soundlist.count{
if NarrationPlayer.isPlaying == true{
}
else{
playSound(soundlist)
counter += 1
}
}
}
@IBAction func StopPlay(_ sender: Any) {
print("stop button worked")
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您遇到的问题是这里的这一行:</p>
<pre><code>while counter < soundlist.count{
</code></pre>
<p>占用了主线程,阻止了对“停止播放”按钮的任何点击。</p>
<p>您已经设置了一个委托(delegate)方法,您可以在这里做的一件非常方便的事情是增加您的计数器并在每次声音文件完成时播放您的下一个声音文件。</p>
<p>类似这样的:</p>
<pre><code>func playSound(_ soundfile: String) {
let NarPath = Bundle.main.path(forResource: soundfile, ofType:"mp3")!
let NarUrl = URL(fileURLWithPath: NarPath)
do {
NarrationPlayer = try AVAudioPlayer(contentsOf: NarUrl)
NarrationPlayer.delegate = self
} catch{
print(error)
}
NarrationPlayer.play()
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
{
playSound(self.soundlist)
counter += 1
}
@IBAction func play(_ sender: Any) {
playSound("first")
soundlist.append("a")
soundlist.append("b")
soundlist.append("c")
}
</code></pre>
<p>最后一条建议:</p>
<p>将名称 <code>NarrationPlayer</code> 更改为 <code>narrationPlayer</code>。 Swift 中的变量,与 Objective-C 中一样,应该以小写字母开头(也称为 lowerCamelCase)。</p></p>
<p style="font-size: 20px;">关于ios - AVAudioPlayer 在播放时不会停止,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/45993011/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/45993011/
</a>
</p>
页:
[1]