简体   繁体   English

当按下不同 UITableView 单元格中的另一个播放按钮时,如何自动停止当前播放音频? - Swift

[英]How to stop currently playing audio automatically when another play button in different UITableView cells are pressed? - Swift

I am a swift beginner currently working on my first iOS app.我是一名 swift 初学者,目前正在开发我的第一个 iOS 应用程序。

I have a TableViewController which has several cells and each cell contains a play button.我有一个 TableViewController,它有几个单元格,每个单元格都包含一个播放按钮。 When a few play buttons are pressed, a few different audios are played at the same time, but I would like to stop a currently playing audio when another playing play button is pressed.当按下几个播放按钮时,会同时播放几个不同的音频,但是当按下另一个正在播放的播放按钮时,我想停止当前正在播放的音频。

Here are the sample codes I created.这是我创建的示例代码。

Please give me an advice.请给我一个建议。 Thank you so much!太感谢了!

The problem is that every single cell has its own independent player.问题是每个细胞都有自己独立的玩家。 You want just one player, so that you can stop it and start a new sound.你只需要一个播放器,这样你就可以停止它并开始一个新的声音。 For example, make the one player a property of the view controller.例如,使一个玩家成为视图 controller 的属性。 Every cell can see it but there is just one.每个细胞都可以看到它,但只有一个。

create an extension for AVPlayer because AVPlayer does not own condition for playing.AVPlayer创建一个扩展,因为AVPlayer不拥有播放条件。 extension given below.下面给出的扩展名。

extension AVPlayer {
    var isPlaying: Bool {
        return rate != 0 && error == nil
    }
}

use it while tap on play like this.像这样点击播放时使用它。

if player?.isPlaying == true {
   player?.pause()
   player?.seek(to: CMTime(seconds: 0, preferredTimescale: 60))
}
//set up you audio file to player
player?.play()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Swift-如何在按下不同UITableView单元格中的另一个播放按钮时自动停止当前播放音频? - Swift - How to stop currently playing audio automatically when another play button in different UITableView cells are pressed? 按下按钮时播放音频 - Playing audio when a button is pressed 按下后退按钮时音频停止播放 - Audio stops playing when back button is pressed 如何在按下按钮时播放音频,而当我将手指从同一按钮上移开时如何立即停止播放? - How can I make audio play when the button is pressed and immediately stop when I take my finger off the same button? 如何真正停止快速播放音频 - How to really stop audio from playing in swift 按下按钮时如何快速播放声音 iOS 15 - How to play sound in swift when button is pressed iOS 15 快速按下按钮时检查是否选择了单元格 - Checking if cells are selected or not when button is pressed swift Audio Queue如何停止当前的播放任务并立即开始播放另一个AudioQueueBuffer? - How Audio Queue stop current playing task and start play another AudioQueueBuffer immediately? 音频停止快速播放后,如何自动更改按钮的背景图像? - How to automatically change background image of a button after audio stops playing in swift? 使用 Swift 中的音频播放器更改 UITableView 中按钮单元的播放暂停状态 - Change Play Pause state of button cell in UITableView with Audio Player in Swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM