Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

macos - AVAudioPlayer.play() does not play sound

Why doesn't the following code play a sound? It returns "true" for play(), but I cannot hear anything.

    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);

If I use the following code instead, I can hear the sound.

    var inFileURL:CFURL = fileURL!;
    var mySound = UnsafeMutablePointer<SystemSoundID>.alloc(sizeof(SystemSoundID));
    AudioServicesCreateSystemSoundID(inFileURL, mySound);
    AudioServicesPlaySystemSound(mySound.memory)
  • OS X Yosemite 10.10.3
  • Xcode 6.2
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that Player, your AVAudioPlayer, is a local variable. So it goes out of existence immediately - before it can even start playing, let alone finish playing.

Solution: make it a property instead, so that it will persist.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...