【问题标题】:Mac - Swift 3 - queuing audio files and playingMac - Swift 3 - 排队音频文件和播放
【发布时间】:2017-07-25 21:11:36
【问题描述】:

我想在 swift 3 中编写一个应用程序,以便在从一个到另一个传递时播放排队的音频文件而没有任何间隙、裂缝或噪音。

我的第一次尝试是使用 AvAudioPlayer 和 AvAudioDelegate (AVAudioPlayer using array to queue audio files - Swift),但我不知道如何预加载下一首歌曲以避免间隙。即使我知道该怎么做,我也不确定这是实现目标的最佳方式。 AVQueuePlayer 似乎是这份工作的更好人选,它是为此目的而制作的,但我没有找到任何可以帮助我的例子。 也许这只是预加载或缓冲的问题?我有点迷失在这充满可能性的海洋中。

欢迎提出任何建议。

【问题讨论】:

  • 除非您平滑地交叉淡入淡出音频文件,否则总会出现裂缝,因为波形不会无缝匹配,而“跳跃”对应于感知声音频谱中的高频。当然,如果音频文件对应于最初是一个不间断声音的各个片段,那么你应该很好......
  • 它们是转换为音频文件的 MIDI 合成样本。它们都以“0”开始,以“0”结束。通过扩大搜索,我找到了一个完美的解决方案。它基于这篇文章:stackoverflow.com/questions/30479403/…。我很快就会发布代码。

标签: swift macos audio avaudioplayer avqueueplayer


【解决方案1】:

它远非完美,特别是如果你想做两次或更多(“文件存在”错误),但它可以作为基础。

它的作用是获取两个文件(我的文件是 ap.4 秒的 aif 样本),将它们编码到一个文件中并播放生成的文件。如果你有数百个,无论是否随意组装,都会很有趣。

mergeAudioFiles 函数的所有功劳归@Peyman 和@Pigeon_39 所有。 Concatenate two audio files in Swift and play them

斯威夫特 3

import Cocoa
import AVFoundation

var action = AVAudioPlayer()
let path = Bundle.main.path(forResource: "audiofile1.aif", ofType:nil)!
let url = URL(fileURLWithPath: path)
let path2 = Bundle.main.path(forResource: "audiofile2.aif", ofType:nil)!
let url2 = URL(fileURLWithPath: path2)
let array1 = NSMutableArray(array: [url, url2])


class ViewController: NSViewController, AVAudioPlayerDelegate
{

    @IBOutlet weak var LanceStop: NSButton!

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }
    override var representedObject: Any?
    {
        didSet
        {
        // Update the view, if already loaded.
        }
    }

    @IBAction func Lancer(_ sender: NSButton)
    {
      mergeAudioFiles(audioFileUrls: array1)
        let url3 = NSURL(string: "/Users/ADDUSERNAMEHERE/Documents/FinalAudio.m4a")

        do
        {
            action = try AVAudioPlayer(contentsOf: url3 as! URL)
            action.delegate = self
            action.numberOfLoops = 0
            action.prepareToPlay()
            action.volume = 1
            action.play()
        }
        catch{print("error")}

    }


    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
    {
        if flag == true
        {

        }
    }

    var mergeAudioURL = NSURL()

    func mergeAudioFiles(audioFileUrls: NSArray) {
        //audioFileUrls.adding(url)
        //audioFileUrls.adding(url2)
        let composition = AVMutableComposition()

        for i in 0 ..< audioFileUrls.count {

            let compositionAudioTrack :AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())

            let asset = AVURLAsset(url: (audioFileUrls[i] as! NSURL) as URL)

            let track = asset.tracks(withMediaType: AVMediaTypeAudio)[0]

            let timeRange = CMTimeRange(start: CMTimeMake(0, 600), duration: track.timeRange.duration)

            try! compositionAudioTrack.insertTimeRange(timeRange, of: track, at: composition.duration)
        }

        let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
        self.mergeAudioURL = documentDirectoryURL.appendingPathComponent("FinalAudio.m4a")! as URL as NSURL

        let assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
        assetExport?.outputFileType = AVFileTypeAppleM4A
        assetExport?.outputURL = mergeAudioURL as URL
        assetExport?.exportAsynchronously(completionHandler:
            {
                switch assetExport!.status
                {
                case AVAssetExportSessionStatus.failed:
                    print("failed \(assetExport?.error)")
                case AVAssetExportSessionStatus.cancelled:
                    print("cancelled \(assetExport?.error)")
                case AVAssetExportSessionStatus.unknown:
                    print("unknown\(assetExport?.error)")
                case AVAssetExportSessionStatus.waiting:
                    print("waiting\(assetExport?.error)")
                case AVAssetExportSessionStatus.exporting:
                    print("exporting\(assetExport?.error)")
                default:
                    print("Audio Concatenation Complete")
                }
        })
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2023-03-17
    • 2017-03-05
    • 2017-03-30
    • 2017-10-09
    • 1970-01-01
    • 2017-03-28
    相关资源
    最近更新 更多