ios - 如何播放本地文件中的音频?

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

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

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

最佳答案

简单 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

关于ios - 如何播放本地文件中的音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55148863/

相关文章:

ios - SMS WatchKit 多个数字分隔符

ios - Swift 对 Java 的 Runnable 的模拟

iphone - 动态实例命名

audio - ffmpeg volumedetect 返回不稳定的结果

iPhone:如何检测 iTunes 是否正在播放?

ios - UIAccessibility - 关闭另一个 View 时,将焦点设置到上一个可访问性元素

ios - swift 内存泄露怎么办?

ios - 使用 Parse Swift 将对象设置为数组

swift - 在 swift 中使用静态 C 库,找不到模块

linux - 找到我可以用 ALSA 玩 PCM 的所有设备