开始&停止声音(提供代码)iOS

时间:2011-11-06 23:23:42

标签: iphone objective-c ios avplayer

我有一个声音,它通过我的服务器通过http播放。然而它成功播放我的服务器,但声音似乎没有停止。我试图编码停止,但我没有运气。帮助赞赏

- (IBAction)oneSound:(id)sender; {
    if (ButtonAlReadyClicked == 1) 
    {
        ButtonAlReadyClicked = 2;

        [sender setBackgroundImage:[UIImage imageNamed:@"m2.png"] forState:UIControlStateNormal];

    }
    else if (ButtonAlReadyClicked == 2) 
    {
        ButtonAlReadyClicked = 1;

        [sender setBackgroundImage:[UIImage imageNamed:@"m1.png"] forState:UIControlStateNormal];

    }  
    if (player && player.playing) {
        [player stop];
        [player release];
        player = nil;
        return;
    }    

    AVPlayer *player = [[AVPlayer playerWithURL:[NSURL URLWithString:@"http://www.mysite.com/hi.mp3"]] retain];

    [player play];

}

我得到的错误是'错误:使用未声明的标识符'播放器'[3]

2 个答案:

答案 0 :(得分:0)

if (player …行始终返回false,因为您有player作为局部变量,而不是实例ivar。将player ivar添加到.h文件中,然后将您初始化的文件保存到其中,而不是保存到本地播放器。

答案 1 :(得分:0)

您需要在.h文件中声明一个名为player的变量,并在单击该按钮时声明实例化播放器。您收到错误的原因是因为在您尝试访问变量及其属性后声明了player变量。

- (IBAction)oneSound:(id)sender {
    if (player == nil) {
        player = [[AVPlayer playerWithURL:[NSURL URLWithString:@"http://www.mysite.com/hi.mp3"]] retain];
        [player play];
        ButtonAlReadyClicked = 1;
        [self oneSound:sender];
        return;
    }
    if (ButtonAlReadyClicked == 1) {
        ButtonAlReadyClicked = 2;
        [sender setBackgroundImage:[UIImage imageNamed:@"m2.png"] forState:UIControlStateNormal];
    }
    else if (ButtonAlReadyClicked == 2) 
    {
        ButtonAlReadyClicked = 1;
        [sender setBackgroundImage:[UIImage imageNamed:@"m1.png"] forState:UIControlStateNormal];
    }  
    if (player && player.playing) {
        [player stop];
        [player release];
        player = nil;
        return;
    }    

}