让AVAudioEngine重复一个声音 [英] Having AVAudioEngine repeat a sound

查看:98
本文介绍了让AVAudioEngine重复一个声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在制作下面的代码时遇到麻烦,一遍又一遍地重复audioURL的声音。现在它只是在视图打开时播放一次,然后停止。

I've been having trouble making the code below repeat the sound at audioURL over and over again. Right now it just plays it once when the view is opened, then stops.

import UIKit
import AVFoundation
class aboutViewController: UIViewController {

    var audioUrl = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("chimes", ofType: "wav")!)
    var audioEngine = AVAudioEngine()
    var myPlayer = AVAudioPlayerNode()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        audioEngine.attachNode(myPlayer)
        var audioFile = AVAudioFile(forReading: audioUrl, error: nil)
        var audioError: NSError?
        audioEngine.connect(myPlayer, to: audioEngine.mainMixerNode, format: audioFile.processingFormat)
        myPlayer.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
        audioEngine.startAndReturnError(&audioError)
        myPlayer.play()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

谢谢!

推荐答案

经过数小时和一小时的搜索,这就做到了:

After hours and hour of searching, this did it:

class aboutViewController: UIViewController {


        var audioEngine: AVAudioEngine = AVAudioEngine()
        var audioFilePlayer: AVAudioPlayerNode = AVAudioPlayerNode()

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.


            let filePath: String = NSBundle.mainBundle().pathForResource("chimes", ofType: "wav")!
            println("\(filePath)")
            let fileURL: NSURL = NSURL(fileURLWithPath: filePath)!
            let audioFile = AVAudioFile(forReading: fileURL, error: nil)
            let audioFormat = audioFile.processingFormat
            let audioFrameCount = UInt32(audioFile.length)
            let audioFileBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: audioFrameCount)
            audioFile.readIntoBuffer(audioFileBuffer, error: nil)

            var mainMixer = audioEngine.mainMixerNode
            audioEngine.attachNode(audioFilePlayer)
            audioEngine.connect(audioFilePlayer, to:mainMixer, format: audioFileBuffer.format)
            audioEngine.startAndReturnError(nil)

            audioFilePlayer.play()
            audioFilePlayer.scheduleBuffer(audioFileBuffer, atTime: nil, options:.Loops, completionHandler: nil)
        }

这篇关于让AVAudioEngine重复一个声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆