ios - 如何在再次单击表格视图时停止歌曲并在单击另一个单元格时播放另一首歌曲
问题描述
我有一些歌曲并在 tableview 中显示。当我按下单元格时,它正在播放歌曲。当我触摸同一个单元格时我想停下来,但如果我触摸另一个单元格,我想让它仍然播放新歌。
extension SoundsViewController: UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCell(withIdentifier: "soundsCell") as! SoundsTableViewCell
cell.soundPicture.image = UIImage(named: "cell1")
cell.soundLabel.text = songs[indexPath.row]
cell.playStopImage.image = UIImage(named: "play")
if selectedItemIndex == indexPath.row {
cell.playStopImage.image = UIImage(named: "pause")
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedItemIndex = indexPath.row
playSong(song: songs[indexPath.row], selectedItemIndex: selectedItemIndex!)
self.myTableView.reloadData()
}
}
func playSong(song: String, selectedItemIndex: Int){
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: song, ofType: "mp3")!))
audioPlayer.numberOfLoops = -1
audioPlayer.play()
var audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}catch{
print(error)
}
}catch{
print(error)
}
}
解决方案
大概你audioPlayer
是你的视图控制器的一个实例变量。
在创建新的 AVAudioPlayer 之前,将您的 playSong 函数更改为调用 audioPlayer.stop()。那应该停止以前的声音。
编辑:
将这样的函数添加到您的视图控制器:
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let selectedRow = tableView.indexPathForSelectedRow {
print("Deselecting row \(selectedRow.row). Stop playing sound")
audioPlayer.stopPlaying()
tableView.deselectRow(at: indexPath, animated: false)
if selectedRow == indexPath {
return nil
}
}
print("Selecting row \(indexPath.row). Start playing sound")
playSong(song: songs[indexPath.row], selectedItemIndex: selectedItemIndex!)
return indexPath
}
推荐阅读
- latex - 如何在 p5.js 中显示漂亮的数学方程式?
- kubernetes-helm - 是否有任何选项告诉 helm 不要等到安装后挂钩完成?
- sql - 执行存储在表列中的 SQL 语句
- python - 存储 flask-jwt 身份验证令牌。我可以/我应该存储在数据库中吗?
- python - 当我尝试运行代码时,它会出错
- bigcommerce - 有没有办法从 BigCommerce 的单个页面中删除站点导航?
- java - 如何配置 WireMock 以将 StubMappings 加载/保存到 AWS S3?
- java - org.springframework.web.HttpRequestMethodNotSupportedException:不支持请求方法“GET”
- c++-cli - 在 ref 类成员中将 System::String^ 转换为 std::string
- intellij-idea - 如何强制 IntelliJ IDEA 将所有 java 文件从空格转换为制表符?