如何从本地文件播放音频?

3

我想播放一个下载的本地音频文件,但是它无法播放:

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")
        }

已下载音频文件到文件管理器,需要从本地路径播放。 - excitedmicrobe
@excitedmicrobe 不起作用。 - SwiftNewling
2个回答

4

简单的解决方案适用于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://dev59.com/XIvda4cB1Zd3GeqPgPbv#35000526


0

只需要添加 .mp3:

let destinationUrl = documentsDirectoryURL.appendingPathComponent("\(reciter.name): \(surah.number).mp3")

1
小心。并不是每个音频文件都是mp3格式的。 - excitedmicrobe
在我的情况下,它们是这样的。因为我正在使用云Firestore存储,并且我自己上传了文件。 - SwiftNewling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接