繁体   English   中英

背景音乐

[英]background music

(使用AVFoundation.framework)

#import "AVFoundation/AVFoundation.h"

所以我遇到了一个问题,我首先在我的类的init方法中尝试了这个代码(这是首先加载的)

NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops=-1;
[player play];

但它没有用,我决定在线程中执行:在init方法中:

[NSThread detachNewThreadSelector:@selector(playMusic) toTarget:self withObject:nil];

和方法本身:

-(void) playMusic {
    NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
    NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
    player.numberOfLoops=-1;
    [player play];
}

它当然是在* .h文件中声明的。 它也没用。

我尝试在线调试

}

playMusic方法文件播放2或3秒然后停止。 没有调试就无法播放。 问题是什么?

AVAudioPlayer将立即解除分配。 你需要留住玩家。 因此,请将AVAudioPlayer设为类的实例变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM