【问题标题】:How to play local song file from local JSON to the app?如何从本地 JSON 播放本地歌曲文件到应用程序?
【发布时间】:2021-09-27 23:42:07
【问题描述】:

我有一个音乐应用程序,它有一个带有自定义单元格的表格视图,其中的标签和信息已经在我的 JSON 文件中:

[
    {
        "loop_name" : "Come Back",
        "Instrument" :"Guitar",
        "loop_link" : "local link to wav file", (need to figure out)
        "producer" : "Bernulli"
    }
]

主要问题是,我不知道如何将本地音频文件实现为 JSON 文件,然后将此数据加载到我的应用程序中。这是我的带有标签的自定义单元格(已经在 J​​SON 文件和按钮中,应该在表格视图的每一行中播放 JSON 文件中的歌曲):

import UIKit
import AVFoundation

protocol CustomSongDelegate: AnyObject {
    func btnUseTap(cell: CustomLoopsCell)
}

class CustomSongCell: UITableViewCell {
    
    weak var delegate: CustomSongDelegate?
    
    var songs: [String] = []
    
    var audioPlayer = AVAudioPlayer()
    
    
    @IBOutlet weak var loopNameLabel: UILabel!
    @IBOutlet weak var producerLabel: UILabel!
    @IBOutlet weak var instrumentLabel: UILabel!
    @IBOutlet weak var playButtonOutlet: UIButton!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    @IBAction func btnUse(_ sender: Any) {
        delegate?.btnUseTap(cell: self)
    }
}

【问题讨论】:

  • 其实JSON只需要文件名,你可以用Bundle.main.url(forResource:”fileName”, withExtension:”mp3”)获取URL或者用FileManager从文档目录中获取。
  • @vadian 所以在 JSON 文件中我应该写歌名还是什么?
  • 磁盘上对应文件的名称。
  • @vadian 例如:songname.wav 并使其看起来像 json:"song_name" : "songname.wav" ???

标签: ios json swift audio avfoundation


【解决方案1】:

从您的 JSON 文件中获取循环本地文件的名称,您可以使用它来播放您的音频:

var player: AVAudioPlayer!

func playLoop(loopLocalFileName: String) {
    let url = Bundle.main.url(forResource: loopLocalFileName, withExtension: "wav") // you should check it for errors
    player = try! AVAudioPlayer(contentsOf: url!) // of course you should catch the error and deal with it...
    player.play()
}

为了更轻松地解析您的 JSON,请尝试使用如下结构:

struct Loop: Codable{
    var name: String
    var instrumentName: String
    var localFileName: String
    var producerName: String
    
    enum CodingKeys: String, CodingKey {
        case name = "loop_name"
        case instrumentName = "Instrument"
        case loopLocalFileName = "loop_link"
        case producerName = "producer"
    }
}

【讨论】:

  • 看起来不错!但是loopLocalFileName,应该是codable struct还是没有?
  • 处理 JSON 的一种好方法是创建一个名为“Loop”的可编码结构,然后您的变量之一将是“localFileName”,如果您在解析 JSON 时遇到问题,请将其写在这里并我会把它添加到我的答案中
  • 我知道怎么做,但我不知道如何正确地为歌曲文件编写它。如果对您来说不难,也许您可​​以从我位于顶部的 json 文件中创建一个示例。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 2013-02-01
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多