如何从本地文件播放音频?
Posted
技术标签:
【中文标题】如何从本地文件播放音频?【英文标题】:How to Play Audio from Local File? 【发布时间】:2019-03-13 18:23:23 【问题描述】:我想播放下载的本地音频文件,但无法播放:
class AVPlayerService
static let instance = AVPlayerService()
private var audioPlayer: AVPlayer!
public weak var delegate: AVPlayerServiceDelegate?
func setupPlayer(forURL url: URL)
let playerItem: AVPlayerItem = AVPlayerItem(url: URL(fileURLWithPath: "\(url)")
audioPlayer = AVPlayer(playerItem: playerItem)
audioPlayer.play()
我在这里获取本地文件,然后在我的视图控制器中调用它:
func getDownloadedSurahFor(surah: Surah, reciter: Reciter) -> (Exists, URL?)
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent("\(reciter.name): \(surah.number)")
print(destinationUrl)
// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path)
print("Already downloaded")
return (.exists, destinationUrl)
else
return (.doesNotExist, nil)
在我的 Viewcontroller 中,我检查它是否存在,然后我调用 setupPlayer:
let (exists, url) = DataService.instance.getDownloadedSurahFor(surah: playingSurah, reciter: reciter)
if exists == .exists
self.audioservice.setupPlayer(forURL: url!)
self.setupSlider()
self.changeButtonTo(.pause)
print("Downloaded file should now play")
【问题讨论】:
重复***.com/questions/54544067/… @excitedmicrobe 不起作用 【参考方案1】:简单适用于 Swift 4+ 的解决方案:
import Foundation
import AVFoundation
final class MediaPlayer
static var player = AVAudioPlayer()
class func play()
do
let file = Bundle.main.url(forResource: "file_name", withExtension: "mp3")!
player = try AVAudioPlayer(contentsOf: file)
player.numberOfLoops = 0 // loop count, set -1 for infinite
player.volume = 1
player.prepareToPlay()
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
try AVAudioSession.sharedInstance().setActive(true)
player.play()
catch _
print("catch")
对于 Swift 4+ 的多次使用:
import UIKit
import AudioToolbox
struct SoundPlayer
static var filename : String?
static var enabled : Bool = true
private struct Internal
static var cache = [URL:SystemSoundID]()
static func playSound(soundFile: String)
if !enabled
return
if let url = Bundle.main.url(forResource: soundFile, withExtension: nil)
var soundID : SystemSoundID = Internal.cache[url] ?? 0
if soundID == 0
AudioServicesCreateSystemSoundID(url as CFURL, &soundID)
Internal.cache[url] = soundID
AudioServicesPlaySystemSound(soundID)
else
print("Could not find sound file name `\(soundFile)`")
// call the function with filename
static func play(file: String)
self.playSound(soundFile: file)
查看此主题以了解 Swift 2 -> https://***.com/a/35000526/2125010
【讨论】:
【参考方案2】:只需要添加.mp3:
let destinationUrl = documentsDirectoryURL.appendingPathComponent("\(reciter.name): \(surah.number).mp3")
【讨论】:
小心。并非每个音频文件都在 mp3 中 就我而言是这样。 Bc 我正在使用云 Firestore 存储,我自己上传了文件以上是关于如何从本地文件播放音频?的主要内容,如果未能解决你的问题,请参考以下文章