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

时间:2019-03-13 18:23:23

标签: ios swift audio avfoundation

我想播放下载的本地音频文件,但不能播放:

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

我在这里获取本地文件,然后在我的viewcontroller中调用它:

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

2 个答案:

答案 0 :(得分:0)

只需添加.mp3:

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

答案 1 :(得分:0)

简单 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://stackoverflow.com/a/35000526/2125010

相关问题