Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Macos AVAudioPlayer.play()不播放声音_Macos_Swift_Audio_Avfoundation - Fatal编程技术网

Macos AVAudioPlayer.play()不播放声音

Macos AVAudioPlayer.play()不播放声音,macos,swift,audio,avfoundation,Macos,Swift,Audio,Avfoundation,为什么下面的代码不播放声音?play()返回“true”,但我什么也听不见 let path = "/Users/account/Music/sound.mp3"; let fileURL = NSURL(fileURLWithPath: path) var Player = AVAudioPlayer(contentsOfURL:fileURL, error:nil); Player.delegate = self; Player.prepareToP

为什么下面的代码不播放声音?play()返回“true”,但我什么也听不见

    let path = "/Users/account/Music/sound.mp3";
    let fileURL = NSURL(fileURLWithPath: path)
    var Player = AVAudioPlayer(contentsOfURL:fileURL, error:nil);

    Player.delegate = self;
    Player.prepareToPlay();
    Player.volume = 1.0;
    var res = Player.play();
    println(res);
如果我使用以下代码,我可以听到声音

    var inFileURL:CFURL = fileURL!;
    var mySound = UnsafeMutablePointer<SystemSoundID>.alloc(sizeof(SystemSoundID));
    AudioServicesCreateSystemSoundID(inFileURL, mySound);
    AudioServicesPlaySystemSound(mySound.memory)
var infieurl:CFURL=fileURL!;
var mySound=unsafemeutablepointer.alloc(sizeof(SystemSoundID));
AudioServicesCreateSystemSoundID(内嵌、mySound);
AudioServicesPlaySystemSound(mySound.memory)
  • 约塞米蒂操作系统10.10.3
  • Xcode 6.2

问题在于,您的AVAudioPlayer是一个局部变量。所以它马上就不存在了——甚至在它开始演奏之前,更不用说结束演奏了


解决方案:将其改为一个属性,这样它将持续存在。

关于局部(自动)变量和属性之间的关键生存期差异,请参阅我的书:我添加了var-Player:AVAudioPlayer=AVAudioPlayer();在功能之外,然后它工作了。